@cortex-js/compute-engine 0.24.1 → 0.25.1

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