@cortex-js/compute-engine 0.24.0 → 0.25.0

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.
Files changed (111) hide show
  1. package/dist/compute-engine.esm.js +25479 -24875
  2. package/dist/compute-engine.js +25480 -24876
  3. package/dist/compute-engine.min.esm.js +13 -13
  4. package/dist/compute-engine.min.js +13 -13
  5. package/dist/math-json.esm.js +6 -3
  6. package/dist/math-json.js +6 -3
  7. package/dist/math-json.min.esm.js +6 -3
  8. package/dist/math-json.min.js +2 -2
  9. package/dist/types/common/ansi-codes.d.ts +1 -1
  10. package/dist/types/common/grapheme-splitter.d.ts +1 -1
  11. package/dist/types/common/signals.d.ts +1 -1
  12. package/dist/types/common/utils.d.ts +1 -1
  13. package/dist/types/compute-engine/assume.d.ts +1 -1
  14. package/dist/types/compute-engine/boxed-expression/abstract-boxed-expression.d.ts +30 -19
  15. package/dist/types/compute-engine/boxed-expression/box.d.ts +9 -9
  16. package/dist/types/compute-engine/boxed-expression/boxed-dictionary.d.ts +4 -4
  17. package/dist/types/compute-engine/boxed-expression/boxed-domain.d.ts +3 -2
  18. package/dist/types/compute-engine/boxed-expression/boxed-function-definition.d.ts +2 -1
  19. package/dist/types/compute-engine/boxed-expression/boxed-function.d.ts +9 -10
  20. package/dist/types/compute-engine/boxed-expression/boxed-number.d.ts +5 -4
  21. package/dist/types/compute-engine/boxed-expression/boxed-patterns.d.ts +2 -15
  22. package/dist/types/compute-engine/boxed-expression/boxed-string.d.ts +3 -4
  23. package/dist/types/compute-engine/boxed-expression/boxed-symbol-definition.d.ts +1 -1
  24. package/dist/types/compute-engine/boxed-expression/boxed-symbol.d.ts +7 -8
  25. package/dist/types/compute-engine/boxed-expression/boxed-tensor.d.ts +6 -7
  26. package/dist/types/compute-engine/boxed-expression/canonical.d.ts +2 -2
  27. package/dist/types/compute-engine/boxed-expression/expression-map.d.ts +1 -1
  28. package/dist/types/compute-engine/boxed-expression/factor.d.ts +11 -0
  29. package/dist/types/compute-engine/boxed-expression/match.d.ts +14 -0
  30. package/dist/types/compute-engine/boxed-expression/numerics.d.ts +41 -0
  31. package/dist/types/compute-engine/boxed-expression/order.d.ts +6 -6
  32. package/dist/types/compute-engine/boxed-expression/public.d.ts +1964 -0
  33. package/dist/types/compute-engine/boxed-expression/serialize.d.ts +3 -15
  34. package/dist/types/compute-engine/boxed-expression/utils.d.ts +5 -2
  35. package/dist/types/compute-engine/boxed-expression/validate.d.ts +7 -6
  36. package/dist/types/compute-engine/collection-utils.d.ts +1 -1
  37. package/dist/types/compute-engine/compile.d.ts +2 -2
  38. package/dist/types/compute-engine/compute-engine.d.ts +83 -60
  39. package/dist/types/compute-engine/cost-function.d.ts +1 -1
  40. package/dist/types/compute-engine/domain-utils.d.ts +3 -2
  41. package/dist/types/compute-engine/function-utils.d.ts +2 -2
  42. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-algebra.d.ts +1 -1
  43. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-arithmetic.d.ts +1 -1
  44. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-calculus.d.ts +1 -1
  45. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-complex.d.ts +1 -1
  46. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-core.d.ts +1 -1
  47. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-linear-algebra.d.ts +1 -1
  48. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-logic.d.ts +1 -1
  49. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-other.d.ts +1 -1
  50. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-relational-operators.d.ts +1 -3
  51. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-sets.d.ts +1 -1
  52. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-statistics.d.ts +1 -1
  53. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-symbols.d.ts +1 -1
  54. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-trigonometry.d.ts +1 -1
  55. package/dist/types/compute-engine/latex-syntax/dictionary/definitions.d.ts +5 -4
  56. package/dist/types/compute-engine/latex-syntax/parse-identifier.d.ts +1 -1
  57. package/dist/types/compute-engine/latex-syntax/parse.d.ts +71 -29
  58. package/dist/types/compute-engine/latex-syntax/public.d.ts +264 -252
  59. package/dist/types/compute-engine/latex-syntax/serialize-number.d.ts +9 -3
  60. package/dist/types/compute-engine/latex-syntax/serializer-style.d.ts +1 -1
  61. package/dist/types/compute-engine/latex-syntax/serializer.d.ts +6 -11
  62. package/dist/types/compute-engine/latex-syntax/tokenizer.d.ts +3 -2
  63. package/dist/types/compute-engine/library/arithmetic-add.d.ts +5 -5
  64. package/dist/types/compute-engine/library/arithmetic-divide.d.ts +2 -1
  65. package/dist/types/compute-engine/library/arithmetic-multiply.d.ts +4 -4
  66. package/dist/types/compute-engine/library/arithmetic-power.d.ts +2 -1
  67. package/dist/types/compute-engine/library/arithmetic.d.ts +1 -1
  68. package/dist/types/compute-engine/library/calculus.d.ts +1 -1
  69. package/dist/types/compute-engine/library/collections.d.ts +1 -1
  70. package/dist/types/compute-engine/library/complex.d.ts +1 -1
  71. package/dist/types/compute-engine/library/control-structures.d.ts +1 -1
  72. package/dist/types/compute-engine/library/core.d.ts +3 -2
  73. package/dist/types/compute-engine/library/domains.d.ts +1 -1
  74. package/dist/types/compute-engine/library/library.d.ts +1 -1
  75. package/dist/types/compute-engine/library/linear-algebra.d.ts +1 -1
  76. package/dist/types/compute-engine/library/logic.d.ts +1 -1
  77. package/dist/types/compute-engine/library/polynomials.d.ts +1 -1
  78. package/dist/types/compute-engine/library/random-expression.d.ts +1 -1
  79. package/dist/types/compute-engine/library/relational-operator.d.ts +1 -2
  80. package/dist/types/compute-engine/library/sets.d.ts +1 -1
  81. package/dist/types/compute-engine/library/statistics.d.ts +1 -1
  82. package/dist/types/compute-engine/library/trigonometry.d.ts +1 -1
  83. package/dist/types/compute-engine/library/utils.d.ts +2 -2
  84. package/dist/types/compute-engine/numerics/numeric-bigint.d.ts +7 -1
  85. package/dist/types/compute-engine/numerics/numeric-bignum.d.ts +1 -1
  86. package/dist/types/compute-engine/numerics/numeric-complex.d.ts +1 -1
  87. package/dist/types/compute-engine/numerics/numeric.d.ts +7 -17
  88. package/dist/types/compute-engine/numerics/primes.d.ts +6 -1
  89. package/dist/types/compute-engine/numerics/rationals.d.ts +4 -13
  90. package/dist/types/compute-engine/numerics/richardson.d.ts +1 -1
  91. package/dist/types/compute-engine/numerics/terms.d.ts +7 -4
  92. package/dist/types/compute-engine/public.d.ts +3 -1839
  93. package/dist/types/compute-engine/rules.d.ts +1 -1
  94. package/dist/types/compute-engine/simplify-rules.d.ts +1 -1
  95. package/dist/types/compute-engine/solve.d.ts +4 -3
  96. package/dist/types/compute-engine/symbolic/derivative.d.ts +1 -1
  97. package/dist/types/compute-engine/symbolic/expand.d.ts +2 -2
  98. package/dist/types/compute-engine/symbolic/flatten.d.ts +6 -4
  99. package/dist/types/compute-engine/symbolic/negate.d.ts +1 -1
  100. package/dist/types/compute-engine/symbolic/polynomials.d.ts +1 -1
  101. package/dist/types/compute-engine/symbolic/product.d.ts +4 -3
  102. package/dist/types/compute-engine/symbolic/tensor-fields.d.ts +1 -1
  103. package/dist/types/compute-engine/symbolic/tensors.d.ts +1 -1
  104. package/dist/types/compute-engine/symbolic/utils.d.ts +5 -10
  105. package/dist/types/compute-engine.d.ts +2 -2
  106. package/dist/types/math-json/math-json-format.d.ts +3 -3
  107. package/dist/types/math-json/utils.d.ts +4 -6
  108. package/dist/types/math-json.d.ts +2 -2
  109. package/package.json +1 -1
  110. package/dist/types/compute-engine/latex-syntax/latex-syntax.d.ts +0 -28
  111. package/dist/types/compute-engine/numerics/factor.d.ts +0 -27
@@ -0,0 +1,1964 @@
1
+ /* 0.25.0 */
2
+ import Decimal from 'decimal.js';
3
+ import { Expression, MathJsonNumber, MathJsonString, MathJsonSymbol, MathJsonFunction, MathJsonDictionary, MathJsonIdentifier } from '../../math-json';
4
+ import type { SerializeLatexOptions, LatexDictionaryEntry, ParseLatexOptions } from '../latex-syntax/public';
5
+ import { IndexedLatexDictionary } from '../latex-syntax/dictionary/definitions';
6
+ import { Rational } from '../numerics/rationals';
7
+ import './serialize';
8
+ /**
9
+ * :::info[THEORY OF OPERATIONS]
10
+ *
11
+ * The `BoxedExpression` interface includes most of the member functions
12
+ * applicable to any kind of expression, for example `get symbol()` or
13
+ * `get ops()`.
14
+ *
15
+ * When a member function is not applicable to this `BoxedExpression`,
16
+ * for example `get symbol()` on a `BoxedNumber`, it returns `null`.
17
+ *
18
+ * This convention makes it convenient to manipulate expressions without
19
+ * having to check what kind of instance they are before manipulating them.
20
+ * :::
21
+ *
22
+ * To get a boxed expression, use `ce.box()` or `ce.parse()`.
23
+ *
24
+ * @category Boxed Expression
25
+ *
26
+ */
27
+ export interface BoxedExpression {
28
+ /** The Compute Engine associated with this expression provides
29
+ * a context in which to interpret it, such as definition of symbols
30
+ * and functions.
31
+ *
32
+ */
33
+ readonly engine: IComputeEngine;
34
+ /** From `Object.valueOf()`, return a primitive value for the expression.
35
+ *
36
+ * If the expression is a machine number, or bignum or rational that can be
37
+ * converted to a machine number, return a JavaScript `number`.
38
+ *
39
+ * If the expression is a symbol, return the name of the symbol as a `string`.
40
+ *
41
+ * Otherwise return a JavaScript primitive representation of the expression.
42
+ *
43
+ * @category Primitive Methods
44
+ */
45
+ valueOf(): number | Object | string | boolean;
46
+ /** From `Object.toString()`, return a string representation of the
47
+ * expression. This string is suitable to be output to the console
48
+ * for debugging, for example. To get a LaTeX representation of the
49
+ * expression, use `expr.latex`.
50
+ *
51
+ * Used when coercing a `BoxedExpression` to a `String`.
52
+ *
53
+ * @category Primitive Methods
54
+ */
55
+ toString(): string;
56
+ /**
57
+ * Output to the console a string representation of the expression.
58
+ *
59
+ * @category Primitive Methods
60
+ */
61
+ print(): void;
62
+ /** Similar to`expr.valueOf()` but includes a hint.
63
+ * @category Primitive Methods
64
+ */
65
+ [Symbol.toPrimitive](hint: 'number' | 'string' | 'default'): number | string | null;
66
+ /** Used by `JSON.stringify()` to serialize this object to JSON.
67
+ *
68
+ * Method version of `expr.json`.
69
+ *
70
+ * @category Primitive Methods
71
+ */
72
+ toJSON(): Expression;
73
+ /** Serialize to a MathJSON expression with specified options*/
74
+ toMathJson(options?: Readonly<Partial<JsonSerializationOptions>>): Expression;
75
+ /** Serialize to a LaTeX string.
76
+ *
77
+ * Will ignore any LaTeX metadata.
78
+ */
79
+ toLatex(options?: Partial<SerializeLatexOptions>): LatexString;
80
+ /** If `true`, this expression is in a canonical form. */
81
+ get isCanonical(): boolean;
82
+ /** For internal use only, set when a canonical expression is created.
83
+ * @internal
84
+ */
85
+ set isCanonical(val: boolean);
86
+ /** MathJSON representation of this expression.
87
+ *
88
+ * This representation always use shorthands when possible. Metadata is not
89
+ * included.
90
+ *
91
+ * Numbers are converted to JavaScript numbers and may lose precision.
92
+ *
93
+ * The expression is represented exactly and no sugaring is applied. For
94
+ * example, `["Power", "x", 2]` is not represented as `["Square", "x"]`.
95
+ *
96
+ * For more control over the serialization, use `ce.serialize()`.
97
+ *
98
+ * :::info[Note]
99
+ * Applicable to canonical and non-canonical expressions.
100
+ * :::
101
+ *
102
+ */
103
+ readonly json: Expression;
104
+ /**
105
+ * The scope in which this expression has been defined.
106
+ * Is null when the expression is not canonical.
107
+ */
108
+ readonly scope: RuntimeScope | null;
109
+ /** From `Object.is()`. Equivalent to `BoxedExpression.isSame()`
110
+ *
111
+ * @category Primitive Methods
112
+ *
113
+ */
114
+ is(rhs: unknown): boolean;
115
+ /** @internal */
116
+ readonly hash: number;
117
+ /** LaTeX representation of this expression.
118
+ *
119
+ * If the expression was parsed from LaTeX, the LaTeX representation is
120
+ * the same as the input LaTeX.
121
+ *
122
+ * Otherwise, the serialization can be customized with `ComputeEngine.latexOptions`
123
+ *
124
+ * :::info[Note]
125
+ * Applicable to canonical and non-canonical expressions.
126
+ * :::
127
+ *
128
+ */
129
+ get latex(): LatexString;
130
+ /**
131
+ *
132
+ * :::info[Note]
133
+ * Applicable to canonical and non-canonical expressions.
134
+ * :::
135
+ * @internal
136
+ */
137
+ set latex(val: LatexString);
138
+ /** If this expression is a symbol, return the name of the symbol as a string.
139
+ * Otherwise, return `null`.
140
+ *
141
+ * :::info[Note]
142
+ * Applicable to canonical and non-canonical expressions.
143
+ * :::
144
+
145
+ * @category Symbol Expression
146
+ *
147
+ */
148
+ readonly symbol: string | null;
149
+ /** If this expression is a string, return the value of the string.
150
+ * Otherwise, return `null`.
151
+ *
152
+ * :::info[Note]
153
+ * Applicable to canonical and non-canonical expressions.
154
+ * :::
155
+
156
+ * @category String Expression
157
+ *
158
+ */
159
+ readonly string: string | null;
160
+ /** All the subexpressions matching the head
161
+ *
162
+ * :::info[Note]
163
+ * Applicable to canonical and non-canonical expressions.
164
+ * :::
165
+ *
166
+ */
167
+ getSubexpressions(head: string): ReadonlyArray<BoxedExpression>;
168
+ /** All the subexpressions in this expression, recursively
169
+ *
170
+ * :::info[Note]
171
+ * Applicable to canonical and non-canonical expressions.
172
+ * :::
173
+ *
174
+ */
175
+ readonly subexpressions: ReadonlyArray<BoxedExpression>;
176
+ /**
177
+ *
178
+ * All the symbols in the expression, recursively
179
+ *
180
+ * :::info[Note]
181
+ * Applicable to canonical and non-canonical expressions.
182
+ * :::
183
+ *
184
+ */
185
+ readonly symbols: ReadonlyArray<string>;
186
+ /**
187
+ * All the identifiers used in the expression that do not have a value
188
+ * associated with them, i.e. they are declared but not defined.
189
+ */
190
+ readonly unknowns: ReadonlyArray<string>;
191
+ /**
192
+ *
193
+ * All the identifiers (symbols and functions) in the expression that are
194
+ * not a local variable or a parameter of that function.
195
+ *
196
+ */
197
+ readonly freeVariables: ReadonlyArray<string>;
198
+ /** All the `["Error"]` subexpressions
199
+ *
200
+ * :::info[Note]
201
+ * Applicable to canonical and non-canonical expressions.
202
+ * :::
203
+ *
204
+ */
205
+ readonly errors: ReadonlyArray<BoxedExpression>;
206
+ /** All boxed expressions have a head.
207
+ *
208
+ * If not a function this can be `Symbol`, `String`, `Number` or `Dictionary`.
209
+ *
210
+ * If the head expression can be represented as a string, it is returned
211
+ * as a string.
212
+ *
213
+ * :::info[Note]
214
+ * Applicable to canonical and non-canonical expressions. The head
215
+ * of a non-canonical expression may be different than the head of its
216
+ * canonical counterpart. For example the canonical counterpart of `["Divide", 5, 7]` is `["Rational", 5, 7]`.
217
+ * :::
218
+
219
+ */
220
+ readonly head: BoxedExpression | string;
221
+ /** The list of arguments of the function, its "tail".
222
+ *
223
+ * If the expression is not a function, return `null`.
224
+ *
225
+ * :::info[Note]
226
+ * Applicable to canonical and non-canonical expressions.
227
+ * :::
228
+ *
229
+ * @category Function Expression
230
+ *
231
+ */
232
+ readonly ops: null | ReadonlyArray<BoxedExpression>;
233
+ /** If this expression is a function, the number of operands, otherwise 0.
234
+ *
235
+ * Note that a function can have 0 operands, so to check if this expression
236
+ * is a function, check if `this.ops !== null` instead.
237
+ *
238
+ * :::info[Note]
239
+ * Applicable to canonical and non-canonical expressions.
240
+ * :::
241
+ *
242
+ * @category Function Expression
243
+ *
244
+ */
245
+ readonly nops: number;
246
+ /** First operand, i.e.`this.ops[0]`
247
+ *
248
+ * :::info[Note]
249
+ * Applicable to canonical and non-canonical expressions.
250
+ * :::
251
+ *
252
+ * @category Function Expression
253
+ *
254
+ *
255
+ */
256
+ readonly op1: BoxedExpression;
257
+ /** Second operand, i.e.`this.ops[1]`
258
+ *
259
+ * :::info[Note]
260
+ * Applicable to canonical and non-canonical expressions.
261
+ * :::
262
+ *
263
+ * @category Function Expression
264
+ *
265
+ *
266
+ */
267
+ readonly op2: BoxedExpression;
268
+ /** Third operand, i.e. `this.ops[2]`
269
+ *
270
+ * :::info[Note]
271
+ * Applicable to canonical and non-canonical expressions.
272
+ * :::
273
+ *
274
+ * @category Function Expression
275
+ *
276
+ *
277
+ */
278
+ readonly op3: BoxedExpression;
279
+ /** `true` if this expression or any of its subexpressions is an `["Error"]`
280
+ * expression.
281
+ *
282
+ * :::info[Note]
283
+ * Applicable to canonical and non-canonical expressions. For
284
+ * non-canonical expression, this may indicate a syntax error while parsing
285
+ * LaTeX. For canonical expression, this may indicate argument domain
286
+ * mismatch, or missing or unexpected arguments.
287
+ * :::
288
+ *
289
+ * @category Symbol Expression
290
+ *
291
+ */
292
+ readonly isValid: boolean;
293
+ /**
294
+ * An exact value is not further transformed when evaluated. To get an
295
+ * approximate evaluation of an exact value, use `.N()`.
296
+ *
297
+ * Exact numbers are:
298
+ * - rationals (including integers)
299
+ * - complex numbers with integer real and imaginary parts (Gaussian integers)
300
+ * - square root of rationals
301
+ *
302
+ * Non-exact values includes:
303
+ * - numbers with a fractional part
304
+ * - complex numbers with a real or imaginary fractional part
305
+ *
306
+ */
307
+ readonly isExact: boolean;
308
+ /** If true, the value of the expression never changes and evaluating it has
309
+ * no side-effects.
310
+ * If false, the value of the expression may change, if the
311
+ * value of other expression changes or for other reasons.
312
+ *
313
+ * If `this.isPure` is `false`, `this.value` is undefined. Call
314
+ * `this.evaluate()` to determine the value of the expression instead.
315
+ *
316
+ * As an example, the `Random` function is not pure.
317
+ *
318
+ * :::info[Note]
319
+ * Applicable to canonical and non-canonical expressions.
320
+ * :::
321
+ */
322
+ readonly isPure: boolean;
323
+ /** True if the expression is a constant, that is a symbol with an immutable value */
324
+ readonly isConstant: boolean;
325
+ /**
326
+ * Return the canonical form of this expression.
327
+ *
328
+ * If this is a function expression, a definition is associated with the
329
+ * canonical expression.
330
+ *
331
+ * When determining the canonical form the following function definition
332
+ * flags are applied:
333
+ * - `associative`: \\( f(a, f(b), c) \longrightarrow f(a, b, c) \\)
334
+ * - `idempotent`: \\( f(f(a)) \longrightarrow f(a) \\)
335
+ * - `involution`: \\( f(f(a)) \longrightarrow a \\)
336
+ * - `commutative`: sort the arguments.
337
+ *
338
+ * If this expression is already canonical, the value of canonical is
339
+ * `this`.
340
+ *
341
+ */
342
+ get canonical(): BoxedExpression;
343
+ /**
344
+ * Replace all the symbols in the expression as indicated.
345
+ *
346
+ * Note the same effect can be achieved with `this.replace()`, but
347
+ * using `this.subs()` is more efficient, and simpler.
348
+ *
349
+ * :::info[Note]
350
+ * Applicable to canonical and non-canonical expressions.
351
+ * :::
352
+ *
353
+ */
354
+ subs(sub: Substitution, options?: {
355
+ canonical?: CanonicalOptions;
356
+ }): BoxedExpression;
357
+ /**
358
+ * Recursively replace all the terms in the expression as indicated.
359
+ *
360
+ * To remove a subexpression, return an empty Sequence expression.
361
+ *
362
+ * The canonical option is applied to each function subexpression after
363
+ * the substitution is applied.
364
+ */
365
+ map(fn: (expr: BoxedExpression) => BoxedExpression, options?: {
366
+ canonical: CanonicalOptions;
367
+ }): BoxedExpression;
368
+ /**
369
+ * Transform the expression by applying the rules:
370
+ *
371
+ * If the expression matches the `match` pattern, replace it with
372
+ * the `replace` pattern.
373
+ *
374
+ * If no rules apply, return `null`.
375
+ *
376
+ * See also `subs` for a simple substitution.
377
+ *
378
+ *
379
+ * :::info[Note]
380
+ * Applicable to canonical and non-canonical expressions. If the
381
+ * expression is non-canonical, the result is also non-canonical.
382
+ * :::
383
+ */
384
+ replace(rules: BoxedRuleSet | Rule | Rule[], options?: ReplaceOptions): null | BoxedExpression;
385
+ /**
386
+ * True if the expression includes a symbol `v` or a function head `v`.
387
+ *
388
+ * :::info[Note]
389
+ * Applicable to canonical and non-canonical expressions.
390
+ * :::
391
+ */
392
+ has(v: string | string[]): boolean;
393
+ /** Structural/symbolic equality (weak equality).
394
+ *
395
+ * `ce.parse('1+x').isSame(ce.parse('x+1'))` is `false`
396
+ *
397
+ * :::info[Note]
398
+ * Applicable to canonical and non-canonical expressions.
399
+ * :::
400
+ *
401
+ * @category Relational Operator
402
+ */
403
+ isSame(rhs: BoxedExpression): boolean;
404
+ /**
405
+ * If this expression matches `pattern`, return a substitution that makes
406
+ * `pattern` equal to `this`. Otherwise return `null`.
407
+ *
408
+ * If `pattern` includes wildcards (identifiers that start
409
+ * with `_`), the substitution will include a prop for each matching named
410
+ * wildcard.
411
+ *
412
+ * If this expression matches `pattern` but there are no named wildcards,
413
+ * return the empty substitution, `{}`.
414
+ *
415
+ * Read more about [**patterns and rules**](/compute-engine/guides/patterns-and-rules/).
416
+ *
417
+ * :::info[Note]
418
+ * Applicable to canonical and non-canonical expressions.
419
+ * :::
420
+ *
421
+ */
422
+ match(pattern: Decimal | Complex | [num: number, denom: number] | SemiBoxedExpression | BoxedExpression, options?: PatternMatchOptions): BoxedSubstitution | null;
423
+ /**
424
+ * "Not a Number".
425
+ *
426
+ * A value representing undefined result of computations, such as `0/0`,
427
+ * as per the floating point format standard IEEE-754.
428
+ *
429
+ * Note that if `isNaN` is true, `isNumber` is also true (yes, `NaN` is a
430
+ * number).
431
+ *
432
+ * @category Numeric Expression
433
+ *
434
+ */
435
+ readonly isNaN: boolean | undefined;
436
+ /**
437
+ * The numeric value of this expression is 0.
438
+ *
439
+ * @category Numeric Expression
440
+ */
441
+ readonly isZero: boolean | undefined;
442
+ /**
443
+ * The numeric value of this expression is not 0.
444
+ * @category Numeric Expression
445
+ */
446
+ readonly isNotZero: boolean | undefined;
447
+ /**
448
+ * The numeric value of this expression is not 1.
449
+ * @category Numeric Expression
450
+ */
451
+ readonly isOne: boolean | undefined;
452
+ /**
453
+ * The numeric value of this expression is not -1.
454
+ * @category Numeric Expression
455
+ */
456
+ readonly isNegativeOne: boolean | undefined;
457
+ /** The numeric value of this expression is ±Infinity or Complex Infinity
458
+ *
459
+ * @category Numeric Expression
460
+ */
461
+ readonly isInfinity: boolean | undefined;
462
+ /** This expression is a number, but not ±Infinity and not `NaN`
463
+ *
464
+ * @category Numeric Expression
465
+ */
466
+ readonly isFinite: boolean | undefined;
467
+ /**
468
+ * @category Numeric Expression
469
+ */
470
+ readonly isEven: boolean | undefined;
471
+ /**
472
+ * @category Numeric Expression
473
+ */
474
+ readonly isOdd: boolean | undefined;
475
+ /**
476
+ * @category Numeric Expression
477
+ */
478
+ readonly isPrime: boolean | undefined;
479
+ /**
480
+ * @category Numeric Expression
481
+ */
482
+ readonly isComposite: boolean | undefined;
483
+ /**
484
+ * Return the value of this expression, if a number literal.
485
+ *
486
+ * Note it is possible for `numericValue` to be `null`, and for `isNotZero`
487
+ * to be true. For example, when a symbol has been defined with an assumption.
488
+ *
489
+ * Conversely, `isNumber` may be true even if `numericValue` is `null`,
490
+ * example the symbol `Pi` return true for `isNumber` but `numericValue` is
491
+ * `null`. Its value can be accessed with `.value.numericValue`
492
+ *
493
+ * @category Numeric Expression
494
+ *
495
+ */
496
+ readonly numericValue: number | Decimal | Complex | Rational | null;
497
+ /** The shape describes the axis of the expression.
498
+ * When the expression is a scalar (number), the shape is `[]`.
499
+ * When the expression is a vector, the shape is `[n]`.
500
+ * When the expression is a matrix, the shape is `[n, m]`.
501
+ */
502
+ readonly shape: number[];
503
+ /** Return 0 for a scalar, 1 for a vector, 2 for a matrix, > 2 for a multidimensional matrix. It's the length of `expr.shape` */
504
+ readonly rank: number;
505
+ /**
506
+ * Return the following, depending on the value of this expression:
507
+ *
508
+ * * `-1` if it is < 0
509
+ * * `0` if it is = 0
510
+ * * `+1` if it is > 0
511
+ * * `undefined` this value may be positive, negative or zero. We don't know
512
+ * right now (a symbol with an Integer domain, but no currently assigned
513
+ * value, for example)
514
+ * * `null` this value will never be positive, negative or zero (`NaN`,
515
+ * a string or a complex number for example)
516
+ *
517
+ * Note that complex numbers have no natural ordering,
518
+ * so if the value is a complex number, `sgn` is either 0, or `null`
519
+ *
520
+ * If a symbol, this does take assumptions into account, that is `this.sgn`
521
+ * will return `1` if `isPositive` is `true`, even if this expression has
522
+ * no value
523
+ *
524
+ * @category Numeric Expression
525
+ *
526
+ */
527
+ readonly sgn: -1 | 0 | 1 | undefined | null;
528
+ /** If the expressions cannot be compared, return `undefined`
529
+ *
530
+ * The numeric value of both expressions are compared.
531
+ *
532
+ * @category Relational Operator
533
+ */
534
+ isLess(rhs: BoxedExpression): boolean | undefined;
535
+ /**
536
+ * The numeric value of both expressions are compared.
537
+ * @category Relational Operator
538
+ */
539
+ isLessEqual(rhs: BoxedExpression): boolean | undefined;
540
+ /**
541
+ * The numeric value of both expressions are compared.
542
+ * @category Relational Operator
543
+ */
544
+ isGreater(rhs: BoxedExpression): boolean | undefined;
545
+ /**
546
+ * The numeric value of both expressions are compared.
547
+ * @category Relational Operator
548
+ */
549
+ isGreaterEqual(rhs: BoxedExpression): boolean | undefined;
550
+ /** The numeric value of this expression is > 0, same as `isGreater(0)`
551
+ *
552
+ * @category Numeric Expression
553
+ */
554
+ readonly isPositive: boolean | undefined;
555
+ /** The numeric value of this expression is >= 0, same as `isGreaterEqual(0)`
556
+ *
557
+ * @category Numeric Expression
558
+ */
559
+ readonly isNonNegative: boolean | undefined;
560
+ /** The numeric value of this expression is < 0, same as `isLess(0)`
561
+ *
562
+ * @category Numeric Expression
563
+ */
564
+ readonly isNegative: boolean | undefined;
565
+ /** The numeric value of this expression is &lt;= 0, same as `isLessEqual(0)`
566
+ *
567
+ * @category Numeric Expression
568
+ */
569
+ readonly isNonPositive: boolean | undefined;
570
+ /** The keys of the dictionary.
571
+ *
572
+ * If this expression not a dictionary, return `null`
573
+ *
574
+ * @category Dictionary Expression
575
+ *
576
+ */
577
+ readonly keys: IterableIterator<string> | null;
578
+ /**
579
+ *
580
+ * @category Dictionary Expression
581
+ */
582
+ readonly keysCount: number;
583
+ /**
584
+ * If this expression is a dictionary, return the value of the `key` entry.
585
+ *
586
+ * @category Dictionary Expression
587
+ *
588
+ */
589
+ getKey(key: string): BoxedExpression | undefined;
590
+ /**
591
+ * If this expression is a dictionary, return true if the
592
+ * dictionary has a `key` entry.
593
+ *
594
+ * @category Dictionary Expression
595
+ *
596
+ */
597
+ hasKey(key: string): boolean;
598
+ /** Wikidata identifier.
599
+ *
600
+ * :::info[Note]
601
+ * `undefined` if not a canonical expression.
602
+ * :::
603
+ */
604
+ readonly wikidata: string | undefined;
605
+ /** An optional short description if a symbol or function expression.
606
+ *
607
+ * May include markdown. Each string is a paragraph.
608
+ *
609
+ * :::info[Note]
610
+ * `undefined` if not a canonical expression.
611
+ * :::
612
+ *
613
+ */
614
+ readonly description: undefined | string[];
615
+ /** An optional URL pointing to more information about the symbol or
616
+ * function head.
617
+ *
618
+ * :::info[Note]
619
+ * `undefined` if not a canonical expression.
620
+ * :::
621
+ *
622
+ */
623
+ readonly url: string | undefined;
624
+ /** Expressions with a higher complexity score are sorted
625
+ * first in commutative functions
626
+ *
627
+ * :::info[Note]
628
+ * `undefined` if not a canonical expression.
629
+ * :::
630
+ */
631
+ readonly complexity: number | undefined;
632
+ /**
633
+ * For symbols and functions, a possible definition associated with the
634
+ * expression. `baseDefinition` is the base class of symbol and function
635
+ * definition.
636
+ *
637
+ * :::info[Note]
638
+ * `undefined` if not a canonical expression.
639
+ * :::
640
+ *
641
+ */
642
+ readonly baseDefinition: BoxedBaseDefinition | undefined;
643
+ /**
644
+ * For functions, a possible definition associated with the expression.
645
+ *
646
+ * :::info[Note]
647
+ * `undefined` if not a canonical expression or not a function.
648
+ * :::
649
+ *
650
+ */
651
+ readonly functionDefinition: BoxedFunctionDefinition | undefined;
652
+ /**
653
+ * For symbols, a possible definition associated with the expression.
654
+ *
655
+ * Return `undefined` if not a symbol
656
+ *
657
+ */
658
+ readonly symbolDefinition: BoxedSymbolDefinition | undefined;
659
+ /**
660
+ *
661
+ * Infer the domain of this expression.
662
+ *
663
+ * If the domain of this expression is already known, return `false`.
664
+ *
665
+ * If the domain was not set, set it to the inferred domain, return `true`
666
+ * If the domain was previously inferred, adjust it by widening it,
667
+ * return `true`
668
+ *
669
+ * @internal
670
+ */
671
+ infer(domain: BoxedDomain): boolean;
672
+ /**
673
+ * Update the definition associated with this expression, using the
674
+ * current scope (`ce.context`).
675
+ *
676
+ * @internal
677
+ */
678
+ bind(): void;
679
+ /**
680
+ *
681
+ * Reset the cached value associated with this expression.
682
+ *
683
+ * Use when the environment has changed, for example the numeric mode
684
+ * or precision, to force the expression to be re-evaluated.
685
+ *
686
+ * @internal
687
+ */
688
+ reset(): void;
689
+ /**
690
+ * Return a simpler form of the canonical form of this expression.
691
+ *
692
+ * A series of rewriting rules are applied repeatedly, until no more rules
693
+ * apply.
694
+ *
695
+ * If a custom `simplify` handler is associated with this function
696
+ * definition, it is invoked.
697
+ *
698
+ * The values assigned to symbols and the assumptions about symbols may be
699
+ * used, for example `arg.isInteger` or `arg.isPositive`.
700
+ *
701
+ * No calculations involving decimal numbers (numbers that are not
702
+ * integers) are performed but exact calculations may be performed,
703
+ * for example:
704
+ *
705
+ * \\( \sin(\frac{\pi}{4}) \longrightarrow \frac{\sqrt{2}}{2} \\).
706
+ *
707
+ * The result is in canonical form.
708
+ *
709
+ */
710
+ simplify(options?: SimplifyOptions): BoxedExpression;
711
+ /**
712
+ * Return the value of the canonical form of this expression.
713
+ *
714
+ * A pure expression always return the same value and has no side effects.
715
+ * If `expr.isPure` is `true`, `expr.value` and `expr.evaluate()` are
716
+ * synonyms.
717
+ *
718
+ * For an impure expression, `expr.value` is undefined.
719
+ *
720
+ * Evaluating an impure expression may have some side effects, for
721
+ * example modifying the `ComputeEngine` environment, such as its set of
722
+ * assumptions.
723
+ *
724
+ * Only exact calculations are performed, no approximate calculations on
725
+ * decimal numbers (non-integer numbers). Constants, rational numbers and
726
+ * square root of rational numbers are preserved.
727
+ *
728
+ * To perform approximate calculations, use `expr.N()` instead.
729
+ *
730
+ * The result of `expr.evaluate()` may be the same as `expr.simplify()`.
731
+ *
732
+ * The result is in canonical form.
733
+ *
734
+ */
735
+ evaluate(options?: EvaluateOptions): BoxedExpression;
736
+ /** Return a numeric approximation of the canonical form of this expression.
737
+ *
738
+ * Any necessary calculations, including on decimal numbers (non-integers),
739
+ * are performed.
740
+ *
741
+ * The calculations are performed according to the `numericMode` and
742
+ * `precision` properties of the `ComputeEngine`.
743
+ *
744
+ * To only perform exact calculations, use `this.evaluate()` instead.
745
+ *
746
+ * If the function is not numeric, the result of `this.N()` is the same as
747
+ * `this.evaluate()`.
748
+ *
749
+ * The result is in canonical form.
750
+ */
751
+ N(options?: NOptions): BoxedExpression;
752
+ compile(to?: 'javascript', options?: {
753
+ optimize: ('simplify' | 'evaluate')[];
754
+ }): ((args: Record<string, any>) => any | undefined) | undefined;
755
+ solve(vars: Iterable<string> | string | BoxedExpression | Iterable<BoxedExpression>): null | ReadonlyArray<BoxedExpression>;
756
+ /**
757
+ * Return a JavaScript primitive representing the value of this expression.
758
+ *
759
+ * Equivalent to `expr.N().valueOf()`.
760
+ *
761
+ */
762
+ get value(): number | boolean | string | Object | undefined;
763
+ /**
764
+ * Only the value of variables can be changed (symbols that are not
765
+ * constants).
766
+ *
767
+ * Throws a runtime error if a constant.
768
+ *
769
+ * :::info[Note]
770
+ * If non-canonical, does nothing
771
+ * :::
772
+ *
773
+ */
774
+ set value(value: boolean | string | Decimal | Complex | {
775
+ re: number;
776
+ im: number;
777
+ } | {
778
+ num: number;
779
+ denom: number;
780
+ } | number[] | BoxedExpression | number | undefined);
781
+ /**
782
+ *
783
+ * The domain of the value of this expression.
784
+ *
785
+ * If a function expression, the domain of the value of the function
786
+ * (the codomain of the function).
787
+ *
788
+ * If a symbol the domain of the value of the symbol.
789
+ *
790
+ * Use `expr.head` to determine if an expression is a symbol or function
791
+ * expression.
792
+ *
793
+ * :::info[Note]
794
+ * If non-canonical or not valid, return `undefined`.
795
+ * :::
796
+ *
797
+ */
798
+ get domain(): BoxedDomain | undefined;
799
+ /** Modify the domain of a symbol.
800
+ *
801
+ * :::info[Note]
802
+ * If non-canonical does nothing
803
+ * :::
804
+ *
805
+ */
806
+ set domain(domain: DomainExpression | BoxedDomain | undefined);
807
+ /** `true` if the value of this expression is a number.
808
+ *
809
+ * `isExtendedComplex || isNaN` = `isReal || isImaginary || isInfinity || isNaN`
810
+ *
811
+ * Note that in a fateful twist of cosmic irony, `NaN` ("Not a Number")
812
+ * **is** a number.
813
+ *
814
+ * @category Domain Properties
815
+ */
816
+ readonly isNumber: boolean | undefined;
817
+ /** The value of this expression is an element of the set ℤ: ...,-2, -1, 0, 1, 2...
818
+ *
819
+ *
820
+ * @category Domain Properties
821
+ *
822
+ */
823
+ readonly isInteger: boolean | undefined;
824
+ /** The value of this expression is an element of the set ℚ, p/q with p ∈ ℕ, q ∈ ℤ ⃰ q >= 1
825
+ *
826
+ * Note that every integer is also a rational.
827
+ *
828
+ *
829
+ * @category Domain Properties
830
+ *
831
+ */
832
+ readonly isRational: boolean | undefined;
833
+ /**
834
+ * The value of this expression is a number that is the root of a non-zero
835
+ * univariate polynomial with rational coefficients.
836
+ *
837
+ * All integers and rational numbers are algebraic.
838
+ *
839
+ * Transcendental numbers, such as \\( \pi \\) or \\( e \\) are not algebraic.
840
+ *
841
+ *
842
+ * @category Domain Properties
843
+ *
844
+ */
845
+ readonly isAlgebraic: boolean | undefined;
846
+ /**
847
+ * The value of this expression is real number: finite and not imaginary.
848
+ *
849
+ * `isFinite && !isImaginary`
850
+ *
851
+ *
852
+ * @category Domain Properties
853
+ */
854
+ readonly isReal: boolean | undefined;
855
+ /** Real or ±Infinity
856
+ *
857
+ * `isReal || isInfinity`
858
+ *
859
+ *
860
+ * @category Domain Properties
861
+ */
862
+ readonly isExtendedReal: boolean | undefined;
863
+ /**
864
+ * The value of this expression is a number, but not `NaN` or any Infinity
865
+ *
866
+ * `isReal || isImaginary`
867
+ *
868
+ *
869
+ * @category Domain Properties
870
+ *
871
+ */
872
+ readonly isComplex: boolean | undefined;
873
+ /** `isReal || isImaginary || isInfinity`
874
+ *
875
+ *
876
+ * @category Domain Properties
877
+ */
878
+ readonly isExtendedComplex: boolean | undefined;
879
+ /** The value of this expression is a number with a imaginary part
880
+ *
881
+ *
882
+ * @category Domain Properties
883
+ */
884
+ readonly isImaginary: boolean | undefined;
885
+ /** Mathematical equality (strong equality), that is the value
886
+ * of this expression and of `rhs` are numerically equal.
887
+ *
888
+ * The numeric value of both expressions are compared.
889
+ *
890
+ * Numbers whose difference is less than `engine.tolerance` are
891
+ * considered equal. This tolerance is set when the `engine.precision` is
892
+ * changed to be such that the last two digits are ignored.
893
+ *
894
+ * @category Relational Operator
895
+ */
896
+ isEqual(rhs: BoxedExpression): boolean;
897
+ }
898
+ /** A semi boxed expression is a MathJSON expression which can include some
899
+ * boxed terms.
900
+ *
901
+ * This is convenient when creating new expressions from portions
902
+ * of an existing `BoxedExpression` while avoiding unboxing and reboxing.
903
+ *
904
+ * @category Boxed Expression
905
+ */
906
+ export type SemiBoxedExpression = number | string | Decimal | Complex | MathJsonNumber | MathJsonString | MathJsonSymbol | MathJsonFunction | MathJsonDictionary | SemiBoxedExpression[] | BoxedExpression;
907
+ /**
908
+ * @category Definitions
909
+ *
910
+ */
911
+ export interface BoxedBaseDefinition {
912
+ name: string;
913
+ wikidata?: string;
914
+ description?: string | string[];
915
+ url?: string;
916
+ /**
917
+ * The scope this definition belongs to.
918
+ *
919
+ * This field is usually undefined, but its value is set by `getDefinition()`
920
+ */
921
+ scope: RuntimeScope | undefined;
922
+ /** When the environment changes, for example the numerical precision,
923
+ * call `reset()` so that any cached values can be recalculated.
924
+ */
925
+ reset(): any;
926
+ }
927
+ /**
928
+ * Use `contravariant` for the arguments of a function.
929
+ * Use `covariant` for the result of a function.
930
+ * Use `bivariant` to check the domain matches exactly.
931
+ *
932
+ * @category Boxed Expression
933
+ */
934
+ export type DomainCompatibility = 'covariant' | 'contravariant' | 'bivariant' | 'invariant';
935
+ /** A domain constructor is the head of a domain expression.
936
+ *
937
+ * @category Boxed Expression
938
+ *
939
+ */
940
+ export type DomainConstructor = 'FunctionOf' | 'ListOf' | 'DictionaryOf' | 'TupleOf' | 'Intersection' | 'Union' | 'OptArg' | 'VarArg' | 'Covariant' | 'Contravariant' | 'Bivariant' | 'Invariant';
941
+ /**
942
+ * @noInheritDoc
943
+ *
944
+ * @category Boxed Expression
945
+ */
946
+ export interface BoxedDomain extends BoxedExpression {
947
+ get canonical(): BoxedDomain;
948
+ get json(): Expression;
949
+ /** True if a valid domain, and compatible with `dom`
950
+ * `kind` is '"covariant"' by default, i.e. `this <: dom`
951
+ */
952
+ isCompatible(dom: BoxedDomain | DomainLiteral, kind?: DomainCompatibility): boolean;
953
+ get base(): DomainLiteral;
954
+ get ctor(): DomainConstructor | null;
955
+ get params(): DomainExpression[];
956
+ readonly isNumeric: boolean;
957
+ readonly isFunction: boolean;
958
+ }
959
+ /**
960
+ * The handlers are the primitive operations that can be performed on
961
+ * collections.
962
+ *
963
+ * There are two types of collections:
964
+ * - finite collections, such as lists, tuples, sets, matrices, etc...
965
+ * The `size()` handler of finite collections returns the number of elements
966
+ * - infinite collections, such as sequences, ranges, etc...
967
+ * The `size()` handler of infinite collections returns `Infinity`
968
+ * Infinite collections are not indexable, they have no `at()` handler.
969
+ *
970
+ * @category Definitions
971
+ */
972
+ export type CollectionHandlers = {
973
+ /** Return an iterator
974
+ * - start is optional and is a 1-based index.
975
+ * - if start is not specified, start from index 1
976
+ * - count is optional and is the number of elements to return
977
+ * - if count is not specified or negative, return all the elements from start to the endna
978
+ *
979
+ * If there is a `keys()` handler, there is no `iterator()` handler.
980
+ *
981
+ * @category Definitions
982
+ */
983
+ iterator: (expr: BoxedExpression, start?: number, count?: number) => Iterator<BoxedExpression, undefined>;
984
+ /** Return the element at the specified index.
985
+ * The first element is `at(1)`, the last element is `at(-1)`.
986
+ * If the index is &lt;0, return the element at index `size() + index + 1`.
987
+ * The index can also be a string for example for dictionaries.
988
+ * If the index is invalid, return `undefined`.
989
+ */
990
+ at: (expr: BoxedExpression, index: number | string) => undefined | BoxedExpression;
991
+ /** Return the number of elements in the collection.
992
+ * An empty collection has a size of 0.
993
+ */
994
+ size: (expr: BoxedExpression) => number;
995
+ /**
996
+ * If the collection is indexed by strings, return the valid values
997
+ * for the index.
998
+ */
999
+ keys: (expr: BoxedExpression) => undefined | Iterator<string>;
1000
+ /**
1001
+ * Return the index of the first element that matches the target expression.
1002
+ * The comparison is done using the `target.isEqual()` method.
1003
+ * If the expression is not found, return `undefined`.
1004
+ * If the expression is found, return the index, 1-based.
1005
+ * If the expression is found multiple times, return the index of the first
1006
+ * match.
1007
+ *
1008
+ * From is the starting index for the search. If negative, start from the end
1009
+ * and search backwards.
1010
+ */
1011
+ indexOf: (expr: BoxedExpression, target: BoxedExpression, from?: number) => number | string | undefined;
1012
+ };
1013
+ /**
1014
+ * A function definition can have some flags to indicate specific
1015
+ * properties of the function.
1016
+ * @category Definitions
1017
+ */
1018
+ export type FunctionDefinitionFlags = {
1019
+ /** If `true`, the function is applied element by element to lists, matrices
1020
+ * (`["List"]` or `["Tuple"]` expressions) and equations (relational
1021
+ * operators).
1022
+ *
1023
+ * **Default**: `false`
1024
+ */
1025
+ threadable: boolean;
1026
+ /** If `true`, `["f", ["f", a], b]` simplifies to `["f", a, b]`
1027
+ *
1028
+ * **Default**: `false`
1029
+ */
1030
+ associative: boolean;
1031
+ /** If `true`, `["f", a, b]` equals `["f", b, a]`. The canonical
1032
+ * version of the function will order the arguments.
1033
+ *
1034
+ * **Default**: `false`
1035
+ */
1036
+ commutative: boolean;
1037
+ /** If `true`, when the function is univariate, `["f", ["Add", x, c]]` where `c`
1038
+ * is constant, is simplified to `["Add", ["f", x], c]`.
1039
+ *
1040
+ * When the function is multivariate, additivity is considered only on the
1041
+ * first argument: `["f", ["Add", x, c], y]` simplifies to `["Add", ["f", x, y], c]`.
1042
+ *
1043
+ * For example, `Log` is additive.
1044
+ *
1045
+ * **Default**: `false`
1046
+ */
1047
+ /** If `true`, when the function is univariate, `["f", ["Multiply", x, y]]`
1048
+ * simplifies to `["Multiply", ["f", x], ["f", y]]`.
1049
+ *
1050
+ * When the function is multivariate, multiplicativity is considered only on the
1051
+ * first argument: `["f", ["Multiply", x, y], z]` simplifies to
1052
+ * `["Multiply", ["f", x, z], ["f", y, z]]`
1053
+ *
1054
+ * **Default**: `false`
1055
+ */
1056
+ /** If `true`, when the function is univariate, `["f", ["Multiply", x, c]]`
1057
+ * simplifies to `["Multiply", ["f", x], c]` where `c` is constant
1058
+ *
1059
+ * When the function is multivariate, multiplicativity is considered only on
1060
+ * the first argument: `["f", ["Multiply", x, y], z]` simplifies to
1061
+ * `["Multiply", ["f", x, z], ["f", y, z]]`
1062
+ *
1063
+ * Default: `false`
1064
+ */
1065
+ /** If `true`, `["f", ["f", x]]` simplifies to `["f", x]`.
1066
+ *
1067
+ * **Default**: `false`
1068
+ */
1069
+ idempotent: boolean;
1070
+ /** If `true`, `["f", ["f", x]]` simplifies to `x`.
1071
+ *
1072
+ * **Default**: `false`
1073
+ */
1074
+ involution: boolean;
1075
+ /** If `true`, the value of this function is always the same for a given
1076
+ * set of arguments and it has no side effects.
1077
+ *
1078
+ * An expression using this function is pure if the function and all its
1079
+ * arguments are pure.
1080
+ *
1081
+ * For example `Sin` is pure, `Random` isn't.
1082
+ *
1083
+ * This information may be used to cache the value of expressions.
1084
+ *
1085
+ * **Default:** `true`
1086
+ */
1087
+ pure: boolean;
1088
+ /**
1089
+ * An inert function evaluates directly to one of its argument, typically
1090
+ * the first one. They may be used to provide formating hints, but do
1091
+ * not affect simplification or evaluation.
1092
+ *
1093
+ * **Default:** false
1094
+ */
1095
+ inert: boolean;
1096
+ /**
1097
+ * All the arguments of a numeric function are numeric,
1098
+ * and its value is numeric.
1099
+ */
1100
+ numeric: boolean;
1101
+ };
1102
+ /** @category Compiling */
1103
+ export type CompiledExpression = {
1104
+ evaluate?: (scope: {
1105
+ [symbol: string]: BoxedExpression;
1106
+ }) => number | BoxedExpression;
1107
+ };
1108
+ /**
1109
+ * @category Definitions
1110
+ *
1111
+ */
1112
+ export type BoxedFunctionSignature = {
1113
+ inferredSignature: boolean;
1114
+ params: BoxedDomain[];
1115
+ optParams: BoxedDomain[];
1116
+ restParam?: BoxedDomain;
1117
+ result: BoxedDomain | ((ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedDomain | null | undefined);
1118
+ canonical?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | null;
1119
+ simplify?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1120
+ evaluate?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1121
+ N?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1122
+ evalDimension?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression;
1123
+ sgn?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => -1 | 0 | 1 | undefined;
1124
+ compile?: (expr: BoxedExpression) => CompiledExpression;
1125
+ };
1126
+ /** @category Definitions */
1127
+ export type Hold = 'none' | 'all' | 'first' | 'rest' | 'last' | 'most';
1128
+ /**
1129
+ * @category Definitions
1130
+ *
1131
+ */
1132
+ export type BoxedFunctionDefinition = BoxedBaseDefinition & Partial<CollectionHandlers> & FunctionDefinitionFlags & {
1133
+ complexity: number;
1134
+ hold: Hold;
1135
+ signature: BoxedFunctionSignature;
1136
+ };
1137
+ /**
1138
+ * @category Definitions
1139
+ *
1140
+ */
1141
+ export type SymbolAttributes = {
1142
+ /**
1143
+ * If `true` the value of the symbol is constant. The value or domain of
1144
+ * symbols with this attribute set to `true` cannot be changed.
1145
+ *
1146
+ * If `false`, the symbol is a variable.
1147
+ *
1148
+ * **Default**: `false`
1149
+ */
1150
+ constant: boolean;
1151
+ /**
1152
+ * If the symbol has a value, it is held as indicated in the table below.
1153
+ * A green checkmark indicate that the symbol is substituted.
1154
+
1155
+ <div className="symbols-table">
1156
+
1157
+ | Operation | `"never"` | `"simplify"` | `"evaluate"` | `"N"` |
1158
+ | :--- | :----- |
1159
+ | `canonical()`| (X) | | | |
1160
+ | `simplify()` | (X) | (X) | | |
1161
+ | `evaluate()` | (X) | (X) | (X) | |
1162
+ | `"N()"` | (X) | (X) | (X) | (X) |
1163
+
1164
+ </div>
1165
+
1166
+ * Some examples:
1167
+ * - `i` has `holdUntil: 'never'`
1168
+ * - `GoldenRatio` has `holdUntil: 'simplify'` (symbolic constant)
1169
+ * - `x` has `holdUntil: 'evaluate'` (variables)
1170
+ * - `Pi` has `holdUntil: 'N'` (special numeric constant)
1171
+ *
1172
+ * **Default:** `evaluate`
1173
+ */
1174
+ holdUntil: 'never' | 'simplify' | 'evaluate' | 'N';
1175
+ };
1176
+ /**
1177
+ * When used in a `SymbolDefinition`, these flags are optional.
1178
+ *
1179
+ * If provided, they will override the value derived from
1180
+ * the symbol's value.
1181
+ *
1182
+ * For example, it might be useful to override `algebraic = false`
1183
+ * for a transcendental number.
1184
+ *
1185
+ * @category Definitions
1186
+ */
1187
+ export type NumericFlags = {
1188
+ number: boolean | undefined;
1189
+ integer: boolean | undefined;
1190
+ rational: boolean | undefined;
1191
+ algebraic: boolean | undefined;
1192
+ real: boolean | undefined;
1193
+ extendedReal: boolean | undefined;
1194
+ complex: boolean | undefined;
1195
+ extendedComplex: boolean | undefined;
1196
+ imaginary: boolean | undefined;
1197
+ positive: boolean | undefined;
1198
+ nonPositive: boolean | undefined;
1199
+ negative: boolean | undefined;
1200
+ nonNegative: boolean | undefined;
1201
+ zero: boolean | undefined;
1202
+ notZero: boolean | undefined;
1203
+ one: boolean | undefined;
1204
+ negativeOne: boolean | undefined;
1205
+ infinity: boolean | undefined;
1206
+ NaN: boolean | undefined;
1207
+ finite: boolean | undefined;
1208
+ even: boolean | undefined;
1209
+ odd: boolean | undefined;
1210
+ prime: boolean | undefined;
1211
+ composite: boolean | undefined;
1212
+ };
1213
+ /**
1214
+ * @noInheritDoc
1215
+ * @category Definitions
1216
+ */
1217
+ export interface BoxedSymbolDefinition extends BoxedBaseDefinition, SymbolAttributes, Partial<NumericFlags> {
1218
+ get value(): BoxedExpression | undefined;
1219
+ set value(val: SemiBoxedExpression | number | undefined);
1220
+ domain: BoxedDomain | undefined;
1221
+ inferredDomain: boolean;
1222
+ }
1223
+ /** @category Rules */
1224
+ export type PatternReplaceFunction = (expr: BoxedExpression, wildcards: BoxedSubstitution) => BoxedExpression;
1225
+ /** @category Rules */
1226
+ export type PatternConditionFunction = (wildcards: BoxedSubstitution, ce: IComputeEngine) => boolean;
1227
+ /**
1228
+ * @noInheritDoc
1229
+ *
1230
+ * @category Pattern Matching
1231
+ */
1232
+ export type Pattern = BoxedExpression;
1233
+ /** @category Rules */
1234
+ export type BoxedRule = {
1235
+ match: Pattern;
1236
+ replace: BoxedExpression | PatternReplaceFunction;
1237
+ condition: undefined | PatternConditionFunction;
1238
+ priority: number;
1239
+ id?: string;
1240
+ };
1241
+ /** @category Rules */
1242
+ export type BoxedRuleSet = ReadonlySet<BoxedRule>;
1243
+ /**
1244
+ * @category Boxed Expression
1245
+ *
1246
+ */
1247
+ export type BoxedSubstitution = Substitution<BoxedExpression>;
1248
+ /**
1249
+ * When provided, canonical forms are used to put an expression in a
1250
+ * "standard" form.
1251
+ *
1252
+ * Each canonical form applies some transformation to an expression. When
1253
+ * specified as an array, each transformation is done in the order in which
1254
+ * it was provided.
1255
+ *
1256
+ * - `InvisibleOperator`: replace use of the `InvisibleOperator` with
1257
+ * another operation, such as multiplication (i.e. `2x` or function
1258
+ * application (`f(x)`).
1259
+ * - `Number`: replace all numeric values with their
1260
+ * canonical representation, for example, reduce
1261
+ * rationals and replace complex numbers with no imaginary part with a real number.
1262
+ * - `Multiply`: replace negation with multiplication by -1, remove 1 from multiplications, simplify signs (`-y \times -x` -> `x \times y`), complex numbers are promoted (['Multiply', 2, 'ImaginaryUnit'] -> `["Complex", 0, 2]`)
1263
+ * - `Add`: replace `Subtract` with `Add`, removes 0 in addition, promote complex numbers (["Add", "a", ["Complex", 0, "b"] -> `["Complex", "a", "b"]`)
1264
+ * - `Power`: simplify `Power` expression, for example, `x^{-1}` -> `\frac{1}{x}`, `x^0` -> `1`, `x^1` -> `x`, `1^x` -> `1`, `x^{\frac{1}{2}}` -> `\sqrt{x}`, `a^b^c` -> `a^{bc}`...
1265
+ * - `Divide`: replace with a `Rational` number if numerator and denominator are integers, simplify, e.g. `\frac{x}{1}` -> `x`...
1266
+ * - `Flatten`: remove any unnecessary `Delimiter` expression, and flatten any associative functions, for example `["Add", ["Add", "a", "b"], "c"]` -> `["Add", "a", "b", "c"]`
1267
+ * - `Order`: when applicable, sort the arguments in a specific order, for
1268
+ * example for addition and multiplication.
1269
+ *
1270
+ *
1271
+ * @category Boxed Expression
1272
+ */
1273
+ export type CanonicalForm = 'InvisibleOperator' | 'Number' | 'Multiply' | 'Add' | 'Power' | 'Divide' | 'Flatten' | 'Order';
1274
+ export type CanonicalOptions = boolean | CanonicalForm | CanonicalForm[];
1275
+ /** @category Boxed Expression */
1276
+ export type DomainLiteral = 'Anything' | 'Values' | 'Domains' | 'Void' | 'NothingDomain' | 'Booleans' | 'Strings' | 'Symbols' | 'Collections' | 'Lists' | 'Dictionaries' | 'Sequences' | 'Tuples' | 'Sets' | 'Functions' | 'Predicates' | 'LogicOperators' | 'RelationalOperators' | 'NumericFunctions' | 'RealFunctions' | 'Numbers' | 'ComplexNumbers' | 'ExtendedRealNumbers' | 'ImaginaryNumbers' | 'Integers' | 'Rationals' | 'PositiveNumbers' | 'PositiveIntegers' | 'NegativeNumbers' | 'NegativeIntegers' | 'NonNegativeNumbers' | 'NonNegativeIntegers' | 'NonPositiveNumbers' | 'NonPositiveIntegers' | 'ExtendedComplexNumbers' | 'TranscendentalNumbers' | 'AlgebraicNumbers' | 'RationalNumbers' | 'RealNumbers';
1277
+ /** @category Boxed Expression */
1278
+ export type DomainExpression<T = SemiBoxedExpression> = DomainLiteral | ['Union', ...DomainExpression<T>[]] | ['Intersection', ...DomainExpression<T>[]] | ['ListOf', DomainExpression<T>] | ['DictionaryOf', DomainExpression<T>] | ['TupleOf', ...DomainExpression<T>[]] | ['OptArg', ...DomainExpression<T>[]] | ['VarArg', DomainExpression<T>] | ['Covariant', DomainExpression<T>] | ['Contravariant', DomainExpression<T>] | ['Bivariant', DomainExpression<T>] | ['Invariant', DomainExpression<T>] | ['FunctionOf', ...DomainExpression<T>[]];
1279
+ /** Options for `BoxedExpression.simplify()`
1280
+ *
1281
+ * @category Compute Engine
1282
+ */
1283
+ export type SimplifyOptions = {
1284
+ recursive?: boolean;
1285
+ rules?: BoxedRuleSet;
1286
+ };
1287
+ /** Options for `BoxedExpression.evaluate()`
1288
+ *
1289
+ * @category Boxed Expression
1290
+ */
1291
+ export type EvaluateOptions = {
1292
+ numericMode?: boolean;
1293
+ };
1294
+ /** Options for `BoxedExpression.N()`
1295
+ *
1296
+ * @category Boxed Expression
1297
+ */
1298
+ export type NOptions = {};
1299
+ /**
1300
+ * The numeric evaluation mode:
1301
+ *
1302
+ <div className="symbols-table">
1303
+
1304
+ | Mode | |
1305
+ | :--- | :----- |
1306
+ | `"auto"`| Use bignum or complex numbers. |
1307
+ | `"machine"` | **IEEE 754-2008**, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision |
1308
+ | `"bignum"` | Arbitrary precision floating point numbers, as provided by the "decimal.js" library |
1309
+ | `"complex"` | Complex number represented by two machine numbers, a real and an imaginary part, as provided by the "complex.js" library |
1310
+
1311
+ </div>
1312
+
1313
+ * @category Compute Engine
1314
+ */
1315
+ export type NumericMode = 'auto' | 'machine' | 'bignum' | 'complex';
1316
+ /**
1317
+ * Metadata that can be associated with a `BoxedExpression`
1318
+ *
1319
+ * @category Boxed Expression
1320
+ */
1321
+ export type Metadata = {
1322
+ latex?: string | undefined;
1323
+ wikidata?: string | undefined;
1324
+ };
1325
+ /**
1326
+ * When a unitless value is passed to or returned from a trigonometric function,
1327
+ * the angular unit of the value.
1328
+ *
1329
+ * - `rad`: radians, 2π radians is a full circle
1330
+ * - `deg`: degrees, 360 degrees is a full circle
1331
+ * - `grad`: gradians, 400 gradians is a full circle
1332
+ * - `turn`: turns, 1 turn is a full circle
1333
+ *
1334
+ * @category Compute Engine
1335
+ */
1336
+ export type AngularUnit = 'rad' | 'deg' | 'grad' | 'turn';
1337
+ /** @category Compute Engine */
1338
+ export type ArrayValue = boolean | number | string | Decimal | Complex | BoxedExpression | undefined;
1339
+ /** @category Assumptions */
1340
+ export type AssumeResult = 'internal-error' | 'not-a-predicate' | 'contradiction' | 'tautology' | 'ok';
1341
+ /** @category Compute Engine */
1342
+ export type AssignValue = boolean | number | string | Decimal | Complex | LatexString | SemiBoxedExpression | ((ce: IComputeEngine, args: any) => BoxedExpression) | undefined;
1343
+ /** @internal */
1344
+ export interface IComputeEngine {
1345
+ latexDictionary: readonly LatexDictionaryEntry[];
1346
+ /** @private */
1347
+ indexedLatexDictionary: IndexedLatexDictionary;
1348
+ decimalSeparator: LatexString;
1349
+ readonly Anything: BoxedDomain;
1350
+ readonly Void: BoxedDomain;
1351
+ readonly Strings: BoxedDomain;
1352
+ readonly Booleans: BoxedDomain;
1353
+ readonly Numbers: BoxedDomain;
1354
+ readonly True: BoxedExpression;
1355
+ readonly False: BoxedExpression;
1356
+ readonly Pi: BoxedExpression;
1357
+ readonly E: BoxedExpression;
1358
+ readonly Nothing: BoxedExpression;
1359
+ readonly Zero: BoxedExpression;
1360
+ readonly One: BoxedExpression;
1361
+ readonly Half: BoxedExpression;
1362
+ readonly NegativeOne: BoxedExpression;
1363
+ readonly I: BoxedExpression;
1364
+ readonly NaN: BoxedExpression;
1365
+ readonly PositiveInfinity: BoxedExpression;
1366
+ readonly NegativeInfinity: BoxedExpression;
1367
+ readonly ComplexInfinity: BoxedExpression;
1368
+ /** @internal */
1369
+ readonly _BIGNUM_NAN: Decimal;
1370
+ /** @internal */
1371
+ readonly _BIGNUM_ZERO: Decimal;
1372
+ /** @internal */
1373
+ readonly _BIGNUM_ONE: Decimal;
1374
+ /** @internal */
1375
+ readonly _BIGNUM_TWO: Decimal;
1376
+ /** @internal */
1377
+ readonly _BIGNUM_HALF: Decimal;
1378
+ /** @internal */
1379
+ readonly _BIGNUM_PI: Decimal;
1380
+ /** @internal */
1381
+ readonly _BIGNUM_NEGATIVE_ONE: Decimal;
1382
+ /** The current scope */
1383
+ context: RuntimeScope | null;
1384
+ /** Absolute time beyond which evaluation should not proceed
1385
+ * @internal
1386
+ */
1387
+ deadline?: number;
1388
+ /** @hidden */
1389
+ readonly timeLimit: number;
1390
+ /** @hidden */
1391
+ readonly iterationLimit: number;
1392
+ /** @hidden */
1393
+ readonly recursionLimit: number;
1394
+ numericMode: NumericMode;
1395
+ tolerance: number;
1396
+ angularUnit: AngularUnit;
1397
+ chop(n: number): number;
1398
+ chop(n: Decimal): Decimal | 0;
1399
+ chop(n: Complex): Complex | 0;
1400
+ chop(n: number | Decimal | Complex): number | Decimal | Complex;
1401
+ bignum: (a: Decimal.Value | bigint) => Decimal;
1402
+ isBignum(a: unknown): a is Decimal;
1403
+ complex: (a: number | Complex, b?: number) => Complex;
1404
+ isComplex(a: unknown): a is Complex;
1405
+ set precision(p: number | 'machine');
1406
+ get precision(): number;
1407
+ costFunction: (expr: BoxedExpression) => number;
1408
+ strict: boolean;
1409
+ box(expr: Decimal | Complex | [num: number, denom: number] | SemiBoxedExpression, options?: {
1410
+ canonical?: CanonicalOptions;
1411
+ }): BoxedExpression;
1412
+ function(head: string | BoxedExpression, ops: ReadonlyArray<SemiBoxedExpression>, options?: {
1413
+ metadata?: Metadata;
1414
+ canonical?: CanonicalOptions;
1415
+ }): BoxedExpression;
1416
+ number(value: number | bigint | string | MathJsonNumber | Decimal | Complex | Rational, options?: {
1417
+ metadata?: Metadata;
1418
+ canonical?: CanonicalOptions;
1419
+ }): BoxedExpression;
1420
+ symbol(sym: string, options?: {
1421
+ metadata?: Metadata;
1422
+ canonical?: CanonicalOptions;
1423
+ }): BoxedExpression;
1424
+ string(s: string, metadata?: Metadata): BoxedExpression;
1425
+ domain(domain: BoxedDomain | DomainExpression, metadata?: Metadata): BoxedDomain;
1426
+ error(message: MathJsonIdentifier | [MathJsonIdentifier, ...ReadonlyArray<SemiBoxedExpression>], where?: SemiBoxedExpression): BoxedExpression;
1427
+ domainError(expectedDomain: BoxedDomain | DomainLiteral, actualDomain: undefined | BoxedDomain, where?: SemiBoxedExpression): BoxedExpression;
1428
+ hold(expr: SemiBoxedExpression): BoxedExpression;
1429
+ add(...ops: ReadonlyArray<BoxedExpression>): BoxedExpression;
1430
+ mul(...ops: ReadonlyArray<BoxedExpression>): BoxedExpression;
1431
+ pow(base: BoxedExpression, exponent: number | Rational | BoxedExpression): BoxedExpression;
1432
+ sqrt(base: BoxedExpression): BoxedExpression;
1433
+ inv(expr: BoxedExpression): BoxedExpression;
1434
+ neg(expr: BoxedExpression): BoxedExpression;
1435
+ div(num: BoxedExpression, denom: BoxedExpression): BoxedExpression;
1436
+ pair(first: BoxedExpression, second: BoxedExpression, metadata?: Metadata): BoxedExpression;
1437
+ tuple(elements: ReadonlyArray<number>, metadata?: Metadata): BoxedExpression;
1438
+ tuple(elements: ReadonlyArray<BoxedExpression>, metadata?: Metadata): BoxedExpression;
1439
+ array(elements: ArrayValue[] | ArrayValue[][], metadata?: Metadata): BoxedExpression;
1440
+ rules(rules: Rule[]): BoxedRuleSet;
1441
+ /**
1442
+ * This is a primitive to create a boxed function.
1443
+ *
1444
+ * In general, consider using `ce.box()` or `canonicalXXX()` instead.
1445
+ *
1446
+ * The caller must ensure that the arguments are in canonical form:
1447
+ * - arguments are `canonical()`
1448
+ * - arguments are sorted
1449
+ * - arguments are flattened and desequenced
1450
+ *
1451
+ * @internal
1452
+ */
1453
+ _fn(head: string | BoxedExpression, ops: ReadonlyArray<BoxedExpression>, options?: Metadata & {
1454
+ canonical?: boolean;
1455
+ }): BoxedExpression;
1456
+ parse(latex: null, options?: Partial<ParseLatexOptions> & {
1457
+ canonical?: CanonicalOptions;
1458
+ }): null;
1459
+ parse(latex: LatexString, options?: Partial<ParseLatexOptions> & {
1460
+ canonical?: CanonicalOptions;
1461
+ }): BoxedExpression;
1462
+ parse(latex: LatexString | null, options?: Partial<ParseLatexOptions> & {
1463
+ canonical?: CanonicalOptions;
1464
+ }): BoxedExpression | null;
1465
+ pushScope(scope?: Partial<Scope>): IComputeEngine;
1466
+ popScope(): IComputeEngine;
1467
+ swapScope(scope: RuntimeScope | null): RuntimeScope | null;
1468
+ resetContext(): void;
1469
+ defineSymbol(name: string, def: SymbolDefinition): BoxedSymbolDefinition;
1470
+ lookupSymbol(name: string, wikidata?: string, scope?: RuntimeScope): undefined | BoxedSymbolDefinition;
1471
+ defineFunction(name: string, def: FunctionDefinition): BoxedFunctionDefinition;
1472
+ lookupFunction(head: string | BoxedExpression, scope?: RuntimeScope | null): undefined | BoxedFunctionDefinition;
1473
+ assign(ids: {
1474
+ [id: string]: AssignValue;
1475
+ }): IComputeEngine;
1476
+ assign(id: string, value: AssignValue): IComputeEngine;
1477
+ assign(arg1: string | {
1478
+ [id: string]: AssignValue;
1479
+ }, arg2?: AssignValue): IComputeEngine;
1480
+ declare(identifiers: {
1481
+ [id: string]: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition;
1482
+ }): IComputeEngine;
1483
+ declare(id: string, def: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition): IComputeEngine;
1484
+ declare(arg1: string | {
1485
+ [id: string]: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition;
1486
+ }, arg2?: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition): IComputeEngine;
1487
+ assume(predicate: SemiBoxedExpression): AssumeResult;
1488
+ forget(symbol?: string | string[]): void;
1489
+ get assumptions(): ExpressionMapInterface<boolean>;
1490
+ ask(pattern: SemiBoxedExpression): BoxedSubstitution[];
1491
+ verify(query: SemiBoxedExpression): boolean;
1492
+ /** @internal */
1493
+ shouldContinueExecution(): boolean;
1494
+ /** @internal */
1495
+ checkContinueExecution(): void;
1496
+ /** @internal */
1497
+ cache<T>(name: string, build: () => T, purge?: (T: any) => T | undefined): T;
1498
+ /** @internal */
1499
+ readonly stats: ComputeEngineStats;
1500
+ /** @internal */
1501
+ reset(): void;
1502
+ /** @internal */
1503
+ _register(expr: BoxedExpression): void;
1504
+ /** @internal */
1505
+ _unregister(expr: BoxedExpression): void;
1506
+ }
1507
+ /** @internal */
1508
+ export interface ComputeEngineStats {
1509
+ symbols: Set<BoxedExpression>;
1510
+ expressions: null | Set<BoxedExpression>;
1511
+ highwaterMark: number;
1512
+ }
1513
+ /**
1514
+ * Options to control the serialization to MathJSON when using `BoxedExpression.json`.
1515
+ *
1516
+ * @category Compute Engine
1517
+ */
1518
+ export type JsonSerializationOptions = {
1519
+ /** If true, the serialization applies some transformations to make
1520
+ * the JSON more readable. For example, `["Power", "x", 2]` is serialized
1521
+ * as `["Square", "x"]`.
1522
+ */
1523
+ prettify: boolean;
1524
+ /** A list of space separated function names that should be excluded from
1525
+ * the JSON output.
1526
+ *
1527
+ * Those functions are replaced with an equivalent, for example, `Square` with
1528
+ * `Power`, etc...
1529
+ *
1530
+ * Possible values include `Sqrt`, `Root`, `Square`, `Exp`, `Subtract`,
1531
+ * `Rational`, `Complex`
1532
+ *
1533
+ * **Default**: `[]` (none)
1534
+ */
1535
+ exclude: string[];
1536
+ /** A list of space separated keywords indicating which MathJSON expressions
1537
+ * can use a shorthand.
1538
+ *
1539
+ * **Default**: `["all"]`
1540
+ */
1541
+ shorthands: ('all' | 'number' | 'symbol' | 'function' | 'dictionary' | 'string')[];
1542
+ /** A list of space separated keywords indicating which metadata should be
1543
+ * included in the MathJSON. If metadata is included, shorthand notation
1544
+ * is not used.
1545
+ *
1546
+ * **Default**: `[]` (none)
1547
+ */
1548
+ metadata: ('all' | 'wikidata' | 'latex')[];
1549
+ /** If true, repeating decimals are detected and serialized accordingly
1550
+ * For example:
1551
+ * - `1.3333333333333333` \( \to \) `1.(3)`
1552
+ * - `0.142857142857142857142857142857142857142857142857142` \( \to \) `0.(1428571)`
1553
+ *
1554
+ * **Default**: `true`
1555
+ */
1556
+ repeatingDecimal: boolean;
1557
+ /**
1558
+ * The maximum number of significant digits in serialized numbers.
1559
+ * - `"max"`: all availabe digits are serialized.
1560
+ * - `"auto"`: use the same precision as the compute engine.
1561
+ *
1562
+ * **Default**: `"auto"`
1563
+ */
1564
+ fractionalDigits: 'auto' | 'max' | number;
1565
+ };
1566
+ /** A LaTeX string starts and end with `$`, for example
1567
+ * `"$\frac{\pi}{2}$"`.
1568
+ *
1569
+ * @category Latex Parsing and Serialization
1570
+ */
1571
+ export type LatexString = string;
1572
+ /**
1573
+ * Control how a pattern is matched to an expression.
1574
+ *
1575
+ * - `substitution`: if present, assumes these values for the named wildcards, and ensure that subsequent occurence of the same wildcard have the same value.
1576
+ * - `recursive`: if true, match recursively, otherwise match only the top level.
1577
+ * - `numericTolerance`: if present, the tolerance for numeric comparison.
1578
+ * - `exact`: if true, only match expressions that are structurally identical. If false, match expressions that are structurally identical or equivalent. For example, when false, `["Add", '_a', 2]` matches `2`, with a value of `_a` of `0`. If true, the expression does not match.
1579
+ *
1580
+ * @category Pattern Matching
1581
+ *
1582
+ */
1583
+ export type PatternMatchOptions = {
1584
+ substitution?: BoxedSubstitution;
1585
+ recursive?: boolean;
1586
+ numericTolerance?: number;
1587
+ exact?: boolean;
1588
+ };
1589
+ /**
1590
+ * @category Boxed Expression
1591
+ *
1592
+ */
1593
+ export type ReplaceOptions = {
1594
+ /** If `true`, apply replacement rules to all sub-expressions.
1595
+ * If `false`, only consider the top-level expression.
1596
+ *
1597
+ * **Default**: `false`
1598
+ */
1599
+ recursive?: boolean;
1600
+ /**
1601
+ * If `true`, stop after the first rule that matches.
1602
+ *
1603
+ * If `false`, apply all the remaining rules even after the first match.
1604
+ *
1605
+ * **Default**: `false`
1606
+ */
1607
+ once?: boolean;
1608
+ /**
1609
+ * If `iterationLimit` > 1, the rules will be repeatedly applied
1610
+ * until no rules apply, up to `maxIterations` times.
1611
+ *
1612
+ * Note that if `once` is true, `maxIterations` has no effect.
1613
+ *
1614
+ * **Default**: `1`
1615
+ */
1616
+ iterationLimit?: number;
1617
+ };
1618
+ /**
1619
+ * A substitution describes the values of the wildcards in a pattern so that
1620
+ * the pattern is equal to a target expression.
1621
+ *
1622
+ * A substitution can also be considered a more constrained version of a
1623
+ * rule whose `lhs` is always a symbol.
1624
+
1625
+ * @category Boxed Expression
1626
+ */
1627
+ export type Substitution<T = SemiBoxedExpression> = {
1628
+ [symbol: string]: T;
1629
+ };
1630
+ /**
1631
+ * A rule describes how to modify an expressions that matches a pattern `match`
1632
+ * into a new expression `replace`.
1633
+ *
1634
+ * `x-1` \( \to \) `1-x`
1635
+ * `(x+1)(x-1)` \( \to \) `x^2-1
1636
+ *
1637
+ * The `match` pattern can be expressed as a LaTeX string or a
1638
+ * MathJSON expression.
1639
+ *
1640
+ *
1641
+ * Anonymous wildcards (`_`) will match any
1642
+ * expression. Named wildcards (`_x`, `_a`, etc...) will match any expression
1643
+ * and bind the expression to the wildcard name.
1644
+ *
1645
+ * In addition the sequence wildcard (`__1`, `__a`, etc...) will match
1646
+ * a sequence of one or more expressions, and bind the sequence to the
1647
+ * wildcard name.
1648
+ *
1649
+ * @category Rules
1650
+ */
1651
+ export type Rule = {
1652
+ match: LatexString | SemiBoxedExpression | Pattern;
1653
+ replace: LatexString | SemiBoxedExpression | PatternReplaceFunction;
1654
+ condition?: LatexString | PatternConditionFunction;
1655
+ priority?: number;
1656
+ id?: string;
1657
+ };
1658
+ /** @category Assumptions */
1659
+ export interface ExpressionMapInterface<U> {
1660
+ has(expr: BoxedExpression): boolean;
1661
+ get(expr: BoxedExpression): U | undefined;
1662
+ set(expr: BoxedExpression, value: U): void;
1663
+ delete(expr: BoxedExpression): void;
1664
+ clear(): void;
1665
+ [Symbol.iterator](): IterableIterator<[BoxedExpression, U]>;
1666
+ entries(): IterableIterator<[BoxedExpression, U]>;
1667
+ }
1668
+ /**
1669
+ * The entries have been validated and optimized for faster evaluation.
1670
+ *
1671
+ * When a new scope is created with `pushScope()` or when creating a new
1672
+ * engine instance, new instances of this type are created as needed.
1673
+ *
1674
+ * @category Definitions
1675
+ */
1676
+ export type RuntimeIdentifierDefinitions = Map<string, BoxedSymbolDefinition | BoxedFunctionDefinition>;
1677
+ /**
1678
+ * A scope is a set of names in a dictionary that are bound (defined) in
1679
+ * a MathJSON expression.
1680
+ *
1681
+ * Scopes are arranged in a stack structure. When an expression that defined
1682
+ * a new scope is evaluated, the new scope is added to the scope stack.
1683
+ * Outside of the expression, the scope is removed from the scope stack.
1684
+ *
1685
+ * The scope stack is used to resolve symbols, and it is possible for
1686
+ * a scope to 'mask' definitions from previous scopes.
1687
+ *
1688
+ * Scopes are lexical (also called a static scope): they are defined based on
1689
+ * where they are in an expression, they are not determined at runtime.
1690
+ *
1691
+ * @category Compute Engine
1692
+ */
1693
+ export type Scope = {
1694
+ /** Signal `timeout` when the execution time for this scope is exceeded.
1695
+ *
1696
+ * Time in seconds, default 2s.
1697
+ *
1698
+ * @experimental
1699
+ */
1700
+ timeLimit: number;
1701
+ /** Signal `out-of-memory` when the memory usage for this scope is exceeded.
1702
+ *
1703
+ * Memory is in Megabytes, default: 1Mb.
1704
+ *
1705
+ * @experimental
1706
+ */
1707
+ memoryLimit: number;
1708
+ /** Signal `recursion-depth-exceeded` when the recursion depth for this
1709
+ * scope is exceeded.
1710
+ *
1711
+ * @experimental
1712
+ */
1713
+ recursionLimit: number;
1714
+ /** Signal `iteration-limit-exceeded` when the iteration limit
1715
+ * in a loop is exceeded. Default: no limits.
1716
+ *
1717
+ * @experimental
1718
+ */
1719
+ iterationLimit: number;
1720
+ };
1721
+ /** @category Compute Engine */
1722
+ export type RuntimeScope = Scope & {
1723
+ parentScope?: RuntimeScope;
1724
+ ids?: RuntimeIdentifierDefinitions;
1725
+ assumptions: undefined | ExpressionMapInterface<boolean>;
1726
+ };
1727
+ /**
1728
+ * A bound symbol (i.e. one with an associated definition) has either a domain
1729
+ * (e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14... domain = TranscendentalNumbers)
1730
+ * @category Definitions
1731
+ */
1732
+ export type SymbolDefinition = BaseDefinition & Partial<SymbolAttributes> & {
1733
+ domain?: DomainLiteral | BoxedDomain;
1734
+ /** If true, the domain is inferred, and could be adjusted later
1735
+ * as more information becomes available or if the symbol is explicitly
1736
+ * declared.
1737
+ */
1738
+ inferred?: boolean;
1739
+ /** `value` can be a JS function since for some constants, such as
1740
+ * `Pi`, the actual value depends on the `precision` setting of the
1741
+ * `ComputeEngine` and possible other environment settings */
1742
+ value?: LatexString | SemiBoxedExpression | ((ce: IComputeEngine) => SemiBoxedExpression | null);
1743
+ flags?: Partial<NumericFlags>;
1744
+ };
1745
+ /**
1746
+ * Definition record for a function.
1747
+ * @category Definitions
1748
+ *
1749
+ */
1750
+ export type FunctionDefinition = BaseDefinition & Partial<CollectionHandlers> & Partial<FunctionDefinitionFlags> & {
1751
+ /**
1752
+ * A number used to order arguments.
1753
+ *
1754
+ * Argument with higher complexity are placed after arguments with lower
1755
+ * complexity when ordered canonically in commutative functions.
1756
+ *
1757
+ * - Additive functions: 1000-1999
1758
+ * - Multiplicative functions: 2000-2999
1759
+ * - Root and power functions: 3000-3999
1760
+ * - Log functions: 4000-4999
1761
+ * - Trigonometric functions: 5000-5999
1762
+ * - Hypertrigonometric functions: 6000-6999
1763
+ * - Special functions (factorial, Gamma, ...): 7000-7999
1764
+ * - Collections: 8000-8999
1765
+ * - Inert and styling: 9000-9999
1766
+ * - Logic: 10000-10999
1767
+ * - Relational: 11000-11999
1768
+ *
1769
+ * **Default**: 100,000
1770
+ */
1771
+ complexity?: number;
1772
+ /**
1773
+ * - `"none"` Each of the arguments is evaluated (default)
1774
+ * - `"all"` None of the arguments are evaluated and they are passed as is
1775
+ * - `"first"` The first argument is not evaluated, the others are
1776
+ * - `"rest"` The first argument is evaluated, the others aren't
1777
+ * - `"last"`: The last argument is not evaluated, the others are
1778
+ * - `"most"`: All the arguments are evaluated, except the last one
1779
+ *
1780
+ * **Default**: `"none"`
1781
+ */
1782
+ hold?: Hold;
1783
+ signature: FunctionSignature;
1784
+ };
1785
+ /**
1786
+ * @category Definitions
1787
+ *
1788
+ */
1789
+ export type BaseDefinition = {
1790
+ /** A short (about 1 line) description. May contain Markdown. */
1791
+ description?: string | string[];
1792
+ /** A URL pointing to more information about this symbol or head. */
1793
+ url?: string;
1794
+ /**
1795
+ * A short string representing an entry in a wikibase.
1796
+ *
1797
+ * For example `Q167` is the [wikidata entry](https://www.wikidata.org/wiki/Q167)
1798
+ * for the `Pi` constant.
1799
+ */
1800
+ wikidata?: string;
1801
+ };
1802
+ /**
1803
+ * @category Definitions
1804
+ *
1805
+ */
1806
+ export type FunctionSignature = {
1807
+ /** The domain of this signature, a domain compatible with the `Functions`
1808
+ * domain).
1809
+ *
1810
+ * @deprecated Use params, optParams, restParam and result instead
1811
+ */
1812
+ domain?: DomainExpression;
1813
+ params?: DomainExpression[];
1814
+ optParams?: DomainExpression[];
1815
+ restParam?: DomainExpression;
1816
+ /** The domain of the result of the function. Either a domain
1817
+ * expression, or a function that returns a boxed domain.
1818
+ */
1819
+ result?: DomainExpression | ((ce: IComputeEngine, args: BoxedDomain[]) => BoxedDomain | null | undefined);
1820
+ /**
1821
+ * Return the canonical form of the expression with the arguments `args`.
1822
+ *
1823
+ * The arguments (`args`) may not be in canonical form. If necessary, they
1824
+ * can be put in canonical form.
1825
+ *
1826
+ * This handler should validate the domain and number of the arguments.
1827
+ *
1828
+ * If a required argument is missing, it should be indicated with a
1829
+ * `["Error", "'missing"]` expression. If more arguments than expected
1830
+ * are present, this should be indicated with an
1831
+ * ["Error", "'unexpected-argument'"]` error expression
1832
+ *
1833
+ * If the domain of an argument is not compatible, it should be indicated
1834
+ * with an `incompatible-domain` error.
1835
+ *
1836
+ * `["Sequence"]` expressions are not folded and need to be handled
1837
+ * explicitly.
1838
+ *
1839
+ * If the function is associative, idempotent or an involution,
1840
+ * this handler should account for it. Notably, if it is commutative, the
1841
+ * arguments should be sorted in canonical order.
1842
+ *
1843
+ * The handler can make transformations based on the value of the arguments
1844
+ * that are exact and literal (i.e.
1845
+ * `arg.numericValue !== null && arg.isExact`).
1846
+ *
1847
+ * Values of symbols should not be substituted, unless they have
1848
+ * a `holdUntil` attribute of `"never"`.
1849
+ *
1850
+ * The handler should not consider the value or any assumptions about any
1851
+ * of the arguments that are symbols or functions (i.e. `arg.isZero`,
1852
+ * `arg.isInteger`, etc...) since those may change over time.
1853
+ *
1854
+ * The result of the handler should be a canonical expression.
1855
+ *
1856
+ * If the arguments do not match, they should be replaced with an appropriate
1857
+ * `["Error"]` expression. If the expression cannot be put in canonical form,
1858
+ * the handler should return `null`.
1859
+ *
1860
+ */
1861
+ canonical?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | null;
1862
+ /**
1863
+ * Rewrite an expression into a simpler form.
1864
+ *
1865
+ * The arguments are in canonical form and have been simplified.
1866
+ *
1867
+ * The handler can use the values assigned to symbols and the assumptions
1868
+ * about symbols, for example with `arg.numericValue`, `arg.isInteger` or
1869
+ * `arg.isPositive`.
1870
+ *
1871
+ * Even though a symbol may not have a value, there may be some information
1872
+ * about it reflected for example in `this.isZero` or `this.isPrime`.
1873
+ *
1874
+ * The handler should not perform approximate numeric calculations, such
1875
+ * as calculations involving decimal numbers (non-integers). Making exact
1876
+ * calculations on integers or rationals is OK.
1877
+ *
1878
+ * Do not reduce constants with a `holdUntil` attribute of `"N"`
1879
+ * or `"evaluate"`.
1880
+ *
1881
+ * This handler should not have any side-effects: do not modify
1882
+ * the environment of the `ComputeEngine` instance, do not perform I/O,
1883
+ * do not do calculations that depend on random values.
1884
+ *
1885
+ * If no simplification can be performed due to the values, domains or
1886
+ * assumptions about its arguments, for example, return `undefined`.
1887
+ *
1888
+ */
1889
+ simplify?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1890
+ /**
1891
+ * Evaluate a function expression.
1892
+ *
1893
+ * The arguments have been evaluated, except the arguments to which a
1894
+ * `hold` applied.
1895
+ *
1896
+ * It is not necessary to further simplify or evaluate the arguments.
1897
+ *
1898
+ * If performing numerical calculations, if all the arguments are exact,
1899
+ * return an exact expression. If any of the arguments is not exact, that is
1900
+ * if it is a literal decimal (non-integer) number, return an approximation.
1901
+ * In this case, the value may be the same as `expr.N()`.
1902
+ *
1903
+ * When doing an exact calculation:
1904
+ * - do not reduce rational numbers to decimal (floating point approximation)
1905
+ * - do not down convert bignums to machine numbers
1906
+ * - do not reduce square roots of rational numbers
1907
+ * - do not reduce constants with a `holdUntil` attribute of `"N"`
1908
+ *
1909
+ * If the expression cannot be evaluated, due to the values, domains, or
1910
+ * assumptions about its arguments, for example, return `undefined` or
1911
+ * an `["Error"]` expression.
1912
+ */
1913
+ evaluate?: SemiBoxedExpression | ((ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined);
1914
+ /**
1915
+ * Evaluate numerically a function expression.
1916
+ *
1917
+ * The arguments `args` have been simplified and evaluated, numerically
1918
+ * if possible, except the arguments to which a `hold` apply.
1919
+ *
1920
+ * The arguments may be a combination of numbers, symbolic
1921
+ * expressions and other expressions.
1922
+ *
1923
+ * Perform as many calculations as possible, and return the result.
1924
+ *
1925
+ * Return `undefined` if there isn't enough information to perform
1926
+ * the evaluation, for example one of the arguments is a symbol with
1927
+ * no value. If the handler returns `undefined`, symbolic evaluation of
1928
+ * the expression will be returned instead to the caller.
1929
+ *
1930
+ * Return `NaN` if there is enough information to perform the
1931
+ * evaluation, but a literal argument is out of range or
1932
+ * not of the expected type.
1933
+ *
1934
+ * Use the value of `ce.numericMode` to determine how to perform
1935
+ * the numeric evaluation.
1936
+ *
1937
+ * Note that regardless of the current value of `ce.numericMode`, the
1938
+ * arguments may be boxed numbers representing machine numbers, bignum
1939
+ * numbers, complex numbers, rationals or big rationals.
1940
+ *
1941
+ * If the numeric mode does not allow complex numbers (the
1942
+ * `engine.numericMode` is not `"complex"` or `"auto"`) and the result of
1943
+ * the evaluation would be a complex number, return `NaN` instead.
1944
+ *
1945
+ * If `ce.numericMode` is `"bignum"` or `"auto"` the evaluation should
1946
+ * be done using bignums.
1947
+ *
1948
+ * Otherwise, `ce.numericMode` is `"machine", the evaluation should be
1949
+ * performed using machine numbers.
1950
+ *
1951
+ * You may perform any necessary computations, including approximate
1952
+ * calculations on floating point numbers.
1953
+ *
1954
+ */
1955
+ N?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1956
+ /** Dimensional analysis
1957
+ * @experimental
1958
+ */
1959
+ evalDimension?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression;
1960
+ /** Return the sign of the function expression. */
1961
+ sgn?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => -1 | 0 | 1 | undefined;
1962
+ /** Return a compiled (optimized) expression. */
1963
+ compile?: (expr: BoxedExpression) => CompiledExpression;
1964
+ };