Compute Engine

module compute-engineClasses

interface BoxedExpression

Extended by Domain, Pattern

Theory of Operations

The BoxedExpression interface includes most of the member functions applicable to any kind of expression, for example get symbol() or get ops().

When a member function is not applicable to this BoxedExpression, for example get symbol() on a BoxedNumber, it returns null.

This convention makes it convenient to manipulate expressions without having to check what kind of instance they are before manipulating them.

interface BoxedExpressionProperties / Methods

Dictionary Expression

Expression Properties

Function Expression

Numeric Expression

String Expression

Symbol Expression

Other

Object Methods

Relational Operator

interface BoxedExpressiondescription: string[]

An optional short description of the symbol or function head.

May include markdown. Each string is a paragraph.

interface BoxedExpressionengine: IComputeEngine

The Compute Engine associated with this expression provides a context in which to interpret it, such as definition of symbols and functions.

interface BoxedExpressionurl: string

An optional URL pointing to more information about the symbol or function head

Dictionary Expression

interface BoxedExpressiongetKey()

getKey(key: string): undefined | BoxedExpression

If this expression is a dictionary, return the value of the key entry.

interface BoxedExpressionhasKey()

hasKey(key: string): boolean

If this expression is a dictionary, return true if the dictionary has a key entry.

interface BoxedExpressionkeys: null | IterableIterator<string>  read only

The keys of the dictionary.

If this expression not a dictionary, return null

interface BoxedExpressionkeysCount: number  read only

Expression Properties

interface BoxedExpressionisAlgebraic: undefined | boolean  read only

The value of this expression is a number that is the root of a non-zero univariate polynomial with rational coefficients.

All integers and rational numbers are algebraic.

Transcendental numbers, such as \( \pi \) or \( e \) are not algebraic.

interface BoxedExpressionisComplex: undefined | boolean  read only

The value of this expression is a number, but not NaN or any Infinity

isReal || isImaginary

interface BoxedExpressionisComposite: undefined | boolean  read only

interface BoxedExpressionisEven: undefined | boolean  read only

interface BoxedExpressionisExtendedComplex: undefined | boolean  read only

isReal || isImaginary || isInfinity

interface BoxedExpressionisExtendedReal: undefined | boolean  read only

Real or ±Infinity

isReal || isInfinity

interface BoxedExpressionisFinite: undefined | boolean  read only

Not ±Infinity and not NaN

interface BoxedExpressionisImaginary: undefined | boolean  read only

The value of this expression is a number with a imaginary part

interface BoxedExpressionisInfinity: undefined | boolean  read only

±Infinity or Complex Infinity

interface BoxedExpressionisInteger: undefined | boolean  read only

The value of this expression is an element of the set ℤ: …,-2, -1, 0, 1, 2…

interface BoxedExpressionisNaN: undefined | boolean  read only

“Not a Number”.

A value representing undefined result of computations, such as 0/0, as per the floating point format standard IEEE-754.

Note that if isNaN is true, isNumber is also true (yes, NaN is a number).

interface BoxedExpressionisNegative: undefined | boolean  read only

The value of this expression is < 0, same as isLess(0)

interface BoxedExpressionisNegativeOne: undefined | boolean  read only

interface BoxedExpressionisNonNegative: undefined | boolean  read only

The value of this expression is >= 0, same as isGreaterEqual(0)

interface BoxedExpressionisNonPositive: undefined | boolean  read only

The value of this expression is <= 0, same as isLessEqual(0)

interface BoxedExpressionisNotZero: undefined | boolean  read only

interface BoxedExpressionisNumber: undefined | boolean  read only

True if the value of this expression is a number.

isExtendedComplex || isNaN = isReal || isImaginary || isInfinity || isNaN

Note that in a fateful twist of cosmic irony, NaN (“Not a Number”) is a number.

interface BoxedExpressionisOdd: undefined | boolean  read only

interface BoxedExpressionisOne: undefined | boolean  read only

interface BoxedExpressionisPositive: undefined | boolean  read only

The value of this expression is > 0, same as isGreater(0)

interface BoxedExpressionisPrime: undefined | boolean  read only

interface BoxedExpressionisRational: undefined | boolean  read only

The value of this expression is an element of the set ℚ, p/q with p ∈ ℕ, q ∈ ℤ ⃰ q >= 1

Note that every integer is also a rational.

interface BoxedExpressionisReal: undefined | boolean  read only

The value of this expression is real number: finite and not imaginary.

isFinite && !isImaginary

interface BoxedExpressionisZero: undefined | boolean  read only

Function Expression

interface BoxedExpressionnops: number  read only

If this expression is a function, the number of operands, otherwise 0.

Note that a function can have 0 operands, so to check if this expression is a function, check if this.ops !== null instead.

interface BoxedExpressionop1: BoxedExpression  read only

First operand, i.e.this.ops[0]

interface BoxedExpressionop2: BoxedExpression  read only

Second operand, i.e.this.ops[0]

interface BoxedExpressionop3: BoxedExpression  read only

Third operand, i.e. this.ops[2]

interface BoxedExpressionops: null | BoxedExpression[]  read only

ops is the list of arguments of the function, its “tail”

Numeric Expression

interface BoxedExpressionasFloat: null | number  read only

Return an approximation of the numeric value of this expression as a 64-bit floating point number.

If the value is a machine number, return it exactly.

If the value is a rational number, return the numerator divided by the denominator.

If the value is a Decimal number that can be represented by a machine number, return this value. There might be a small loss of precision due to the limitations of the binary representation of numbers as machine numbers.

If the value of this expression cannot be represented by a float, return null.

interface BoxedExpressionasRational: [null, null] | [number, number]  read only

If the value of this an expression is a small integer or a rational, return this value. Otherwise, return [null, null].

interface BoxedExpressionasSmallInteger: null | number  read only

If the value of this expression is an integer with a ‘small’ absolute value, return this value. Otherwise, return null.

Some calculations, for example to put in canonical forms, are only performed if they are safe from overflow. This method makes it easy to check for this, whether the value is a Decimal or a number.

By default, “small” is less than 10,000.

interface BoxedExpressioncomplexValue: null | Complex  read only

If the value of this expression is a Complex number, return it. Otherwise, return null.

If complexValue is not null, then machineValue, rationalValue and decimalValue are `null.

interface BoxedExpressiondecimalValue: null | Decimal  read only

If the value of this expression is a Decimal number, return it. Otherwise, return null.

A Decimal number is an arbitrarily long floating point number.

If decimalValue is not null, then machineValue and complexValue are null and rationalValue is [null, null].

interface BoxedExpressionmachineValue: null | number  read only

Return the value of this number or symbol, if stored as a machine number.

Note it is possible for machineValue to be null, and for isNotZero to be true. For example, when a symbol has been defined with an assumption.

If machineValue is not null, then decimalValue, rationalValue and complexValue are `null.

interface BoxedExpressionrationalValue: [numer: number, denom: number] | [null, null]  read only

If the value of this expression is a rational number, return it. Otherwise, return [null, null].

If rationalValue is not [null, null], then machineValue, decimalValue and complexValue are `null.

interface BoxedExpressionsgn: undefined | null | 0 | 1 | -1  read only

Return the following, depending on the value of this expression:

  • -1 if it is < 0
  • 0 if it is = 0
  • +1 if it is > 0
  • undefined this value may be positive, negative or zero. We don’t know right now (a symbol with an Integer domain, but no currently assigned value, for example)
  • null this value will never be positive, negative or zero (NaN, a string or a complex number for example)

Note that complex numbers have no natural ordering, so if the value is a complex number, sgn is either 0, or null

If a symbol, this does take assumptions into account, that is this.sgn will return 1 if isPositive is true, even if this expression has no value

String Expression

interface BoxedExpressionstring: null | string  read only

If this expression is a string, return the value of the string. Otherwise, return null.

Symbol Expression

interface BoxedExpressionisMissing: boolean  read only

Shortcut for this.symbol === "Missing"

interface BoxedExpressionsymbol: null | string  read only

If this expression is a symbol, return the name of the symbol as a string. Otherwise, return null.

Other

interface BoxedExpressionN()

N(options?: NOptions): BoxedExpression

Return a numeric approximation of this expression.

The expression is first converted to canonical form.

Any necessary calculations, including on floating point numbers, are performed. The calculations are performed according to the numericMode and precision properties of the ComputeEngine.

To only perform exact calculations, use this.evaluate() instead.

If the function is not numeric, the result of this.N() is the same as this.evaluate().

The result is in canonical form.

interface BoxedExpressionapply()

apply(fn: (x: BoxedExpression): SemiBoxedExpression, head?: string): BoxedExpression

If this expression is a function, apply the function fn to all its operands. Replace the head of this expression with head, if defined.

If this expression is a dictionary, return a new dictionary with the values modified by fn.

If head is provided, return a function with the modified dictionary as operand, otherwise return the modified dictionary.

interface BoxedExpressioncanonical: BoxedExpression  read only

Return the canonical form of this expression.

If a function, consider the function definition flags:

  • associative: \( f(a, f(b), c) \longrightarrow f(a, b, c) \)
  • idempotent: \( f(f(a)) \longrightarrow f(a) \)
  • involution: \( f(f(a)) \longrightarrow a \)
  • commutative: sort the arguments.

Additionally, some simplifications involving exact computations on small integers may be performed.

For example:

  • \( 2 + x + 1 \longrightarrow x + 3 \)
  • \( \sqrt{4} \longrightarrow 2 \)
  • \(\frac{4}{10} \longrightarrow \frac{2}{5} \).

However, no calculation is performed involving floating point numbers, so \( \sqrt(2) \longrightarrow \sqrt(2) \).

Determining the canonical form does not depend on the values assigned to, or assumptions about, symbols.

interface BoxedExpressioncomplexity: number  read only

Expressions with a higher complexity score are sorted first in commutative functions

interface BoxedExpressiondomain

get domain(): Domain
set domain(string | Domain)

The domain of this expression.

Symbols that represent a variable, can have their domain modified

interface BoxedExpressionevaluate()

evaluate(options?: EvaluateOptions): BoxedExpression

Return the value of this expression.

The expression is first converted to canonical form.

A pure expression always return the same value and has no side effects. If this.isPure is true, this.value and this.evaluate() are synonyms. For an impure expression, this.value is undefined.

Evaluating an impure expression may have some side effects, for example modifying the ComputeEngine environment, such as its set of assumptions.

Only exact calculations are performed, no floating point calculations. To perform approximate floating point calculations, use this.N() instead.

The result of this.evaluate() may be the same as this.simplify().

The result is in canonical form.

interface BoxedExpressionfunctionDefinition: undefined | BoxedFunctionDefinition  read only

For symbols and functions, a possible definition associated with the expression

interface BoxedExpressionhas()

has(v: string | string[]): boolean

True if the expression includes a symbol v or a function head v.

interface BoxedExpressionhead: string | BoxedExpression  read only

All boxed expressions have a head.

If not a function this can be Symbol, String, Number or Dictionary.

If the head expression can be represented as a string, it is returned as a string.

interface BoxedExpressionisCanonical: boolean

If true, this expression is in a canonical form

interface BoxedExpressionisLiteral: boolean  read only

If true, this expression represents a value that was not calculated or that does not reference another expression. This means the expression is either a number, a string or a dictionary. Functions and symbols are not literals.

interface BoxedExpressionisPure: boolean  read only

If true, the value of the expression never changes and evaluating it has no side-effects. If false, the value of the expression may change, if the value of other expression changes or for other reasons.

If this.isPure is false, this.value is undefined. Call this.evaluate() to determine the value of the expression instead.

As an example, the Random function is not pure.

interface BoxedExpressionjson: Expression  read only

MathJSON representation of this expression

interface BoxedExpressionlatex: string

LaTeX representation of this expression

interface BoxedExpressionmatch()

match(rhs: BoxedExpression, options?: PatternMatchOption): null | Substitution

Attempt to match this expression to the rhs expression.

If rhs does not match, return null.

Otherwise return an object literal.

If this expression includes wildcards (symbols with a name that starts with _), the object literal will include a prop for each matching named wildcard.

If rhs matches this pattern but there are no named wildcards, return the empty object literal, {}.

interface BoxedExpressionnumericValue: undefined | BoxedExpression  read only

Return an approximation of the value of this expression. Floating-point operations may be performed.

Just like this.value, it returns undefined for impure expressions.

interface BoxedExpressionreplace()

replace(rules: BoxedRuleSet, options?: ReplaceOptions): null | BoxedExpression

Transform the expression by according to the rules: the matching lhs of a rule is replaced by its rhs.

If no rules apply, return null.

See also subs for a simple substitution.

interface BoxedExpressionsimplify()

simplify(options?: {recursive: boolean; rules: BoxedRuleSet}): BoxedExpression

Return a simpler form of this expression.

The expression is first converted to canonical form. Then a series of rewriting rules are applied repeatedly, until no rules apply.

If a custom simplify handler is associated with this function definition, it is invoked.

The values assigned to symbols and the assumptions about symbols may be used, for example arg.isInteger or arg.isPositive.

No calculations involving floating point numbers are performed but exact calculations may be performed, for example \( \sin(\frac{\pi}{4}) \longrightarrow \frac{\sqrt{2}}{2} \).

The result is in canonical form.

interface BoxedExpressionsolve()

solve(vars: Iterable<string>): null | BoxedExpression[]

interface BoxedExpressionsubs()

Replace all the symbols in the expression as indicated.

Note the same effect can be achieved with this.replace(), but using this.subs() is more efficient, and simpler.

interface BoxedExpressionsymbolDefinition: undefined | BoxedSymbolDefinition  read only

interface BoxedExpressionvalue

get value(): undefined | BoxedExpression
set value(undefined | number | BoxedExpression)

If this.isPure is true, this is a synonym for this.evaluate(). Otherwise, it returns undefined.

Only the value of variables can be changed (symbols that are not constants)

interface BoxedExpressionvalueDomain: Domain  read only

The domain of the value of this expression, using the value of the expression, definitions associated with this expression and assumptions if necessary.

For symbols, the domain and valueDomain are the same. For functions, the valueDomain is the codomain of the function.

interface BoxedExpressionwikidata: string

Wikidata identifier

Object Methods

interface BoxedExpressionis()

is(rhs: unknown): boolean

From Object.is(). Equivalent to BoxedExpression.isSame()

interface BoxedExpressiontoJSON()

toJSON(): string

From Object.toJSON(), equivalent to JSON.stringify(this.json)

interface BoxedExpressiontoString()

toString(): string

From Object.toString(), return a LaTeX representation of the expression.

interface BoxedExpressionvalueOf()

valueOf(): string | number | [number, number]

From Object.valueOf(), return a primitive value for the expression.

If the expression is a machine number, or a Decimal that can be converted to a machine number, return a number.

If the expression is a rational number, return [number, number].

If the expression is a symbol, return the name of the symbol as a string.

Otherwise return a LaTeX representation of the expression.

Relational Operator

interface BoxedExpressionisEqual()

isEqual(rhs: BoxedExpression): boolean

Mathematical equality (strong equality), that is the value of this expression and of rhs are numerically equal.

Both expressions are numerically evaluated.

Numbers whose difference is less than engine.tolerance are considered equal. This tolerance is set when the engine.precision is changed to be such that the last two digits are ignored.

interface BoxedExpressionisGreater()

isGreater(rhs: BoxedExpression): undefined | boolean

interface BoxedExpressionisGreaterEqual()

isGreaterEqual(rhs: BoxedExpression): undefined | boolean

interface BoxedExpressionisLess()

isLess(rhs: BoxedExpression): undefined | boolean

If the expressions cannot be compared, undefined is returned

interface BoxedExpressionisLessEqual()

isLessEqual(rhs: BoxedExpression): undefined | boolean

interface BoxedExpressionisSame()

isSame(rhs: BoxedExpression): boolean

Structural/symbolic equality (weak equality).

ce.parse('1+x').isSame(ce.parse('x+1')) is false

interface BoxedSymbolDefinition

interface BoxedSymbolDefinitionProperties / Methods

interface BoxedSymbolDefinitionat()

at(index: string | number): undefined | BoxedExpression

interface BoxedSymbolDefinitionvalue: undefined | BoxedExpression

class ComputeEngine

Implements IComputeEngine

To use the CortexJS Compute Engine, create a ComputeEngine instance.

Use the instance to create expressions with ce.parse() and ce.box().

const ce = new ComputeEngine();
let expr = ce.parse("e^{i\\pi}");
console.log(expr.N().latex);
// ➔ "-1"

expr = ce.box(["Expand", ["Power", ["Add", "a", "b"], 2]]);
console.log(expr.evaluate().latex);
// ➔ "a^2 +  2ab + b^2"

class ComputeEnginenew ComputeEngine()

new ComputeEngine(options?)
options?:
assumptions: Expression[];
defaultDomain: string;

If an unknown symbol is encountered, assume it should be a variable in this domain. Default ExtendedRealNumber

dictionaries: Readonly<Dictionary>[];
latexDictionary: readonly LatexDictionaryEntry[];
numericMode: NumericMode;

The default mode is auto. Use machine to only use 64-bit float, use decimal to always use arbitrary precision floating point numbers or complex for complex numbers.

numericPrecision: number;

Specific how many digits of precision for the numeric calculations. Default is 100.

tolerance: number;

If the absolute value of the difference of two numbers is less than toleranc, they are considered equal. Used by chop() as well.

ComputeEngine

Construct a new ComputeEngine instance.

Dictionaries define functions and symbols (in options.dictionaries) and the LaTeX syntax (in options.latexDictionaries). If no dictionaries are provided, the default ones are used.

The order of the dictionaries matter: the definitions from the later ones override the definitions from earlier ones. The first dictionary should be the 'core' dictionary which include some basic definitions such as domains (Boolean, Number, etc…) that are used by later dictionaries.

class ComputeEngineProperties / Methods

class ComputeEngineadd()

add(ops: BoxedExpression[], metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Add"...).

The result is canonical.

class ComputeEngineask()

Return a list of all the assumptions that match a pattern.

 ce.assume(x, 'PositiveInteger');
 ce.ask(['Greater', 'x', '_val'])
 //  -> [{'val': 0}]

class ComputeEngineassert()

assert(condition: boolean, expr: BoxedExpression, msg: string, code?: SignalMessage): void

When condition is false, signal.

  • condition - If true, do nothing. If false, signal.

class ComputeEngineassume()

assume(symbol: SemiBoxedExpression, domain: string | BoxedExpression): AssumeResult

Add an assumption.

Note that the assumption is put into canonical form before being added.


assume(predicate: SemiBoxedExpression): AssumeResult

class ComputeEngineassumptions: ExpressionMapInterface<boolean>  read only

class ComputeEnginebox()

box(expr: [num: number, denom: number] | SemiBoxedExpression): BoxedExpression

Returned a boxed expression from the input.

The result may not be canonical.

class ComputeEnginechop()

chop(n: number): number

Replace a number that is close to 0 with the exact integer 0.

How close to 0 the number has to be to be considered 0 is determined by tolerance.


chop(n: Decimal): 0 | Decimal

chop(n: Complex): 0 | Complex

class ComputeEnginecontext: RuntimeScope

The current scope.

A scope stores the definition of symbols and assumptions.

Scopes form a stack, and definitions in more recent scopes can obscure definitions from older scopes.

The ce.context property represents the current scope.

class ComputeEnginecostFunction

get costFunction(): (expr: BoxedExpression): number
set costFunction(undefined | (expr: BoxedExpression): number)

class ComputeEnginedefaultDomain

get defaultDomain(): null | Domain
set defaultDomain(null | string | Domain)

If an unknown symbol is encountered, assume it should be a variable in this domain.

If set to null, unknown symbols will trigger an error.

Default: "ExtendedRealNumber"

class ComputeEnginedefineSymbol()

Add (or replace) a definition for a symbol in the current scope.

class ComputeEnginedivide()

divide(num: BoxedExpression, denom: BoxedExpression, metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Divide", [num, denom])

The result is canonical.

class ComputeEnginedomain()

domain(domain: BoxedExpression | Domain | DomainExpression, metadata?: Metadata): Domain

Return a canonical boxed domain

class ComputeEngineerror()

error(val: BoxedExpression, message: string, messageArg: SemiBoxedExpression): BoxedExpression

Shortcut for this.fn("Error"...).

The result is canonical.

class ComputeEnginefn()

fn(head: string, ops: BoxedExpression[], metadata?: Metadata): BoxedExpression

Return a canonical expression.

Note that the result may not be a function, or may have a different head than the one specified.

For example ce.fn("Add", [ce.number(2), ce.number(3)])) ( \to ) 5

class ComputeEngineforget()

forget(symbol: undefined | string | string[]): void

Remove all assumptions about one or more symbols

class ComputeEnginegetDictionaries()

getDictionaries(categories: DictionaryCategory[] | "all"): Readonly<Dictionary>[]

Return dictionaries suitable for the specified categories, or "all" for all categories ("arithmetic", "algebra", etc…).

A symbol dictionary defines how the symbols and function names in a MathJSON expression should be interpreted, i.e. how to evaluate and manipulate them.

class ComputeEnginegetFunctionDefinition()

getFunctionDefinition(head: string, args?: BoxedExpression[]): undefined | BoxedFunctionDefinition

Return the definition for a function matching this head and these arguments.

Start looking in the current scope, than up the scope chain.

class ComputeEnginegetLatexDictionary()

getLatexDictionary(domain: DictionaryCategory | "all"): readonly LatexDictionaryEntry[]

class ComputeEnginegetSymbolDefinition()

getSymbolDefinition(symbol: string, wikidata?: string): undefined | BoxedSymbolDefinition

Return a matching symbol definition, starting with the current scope and going up the scope chain.

class ComputeEngineinverse()

inverse(expr: BoxedExpression, metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Divide", [1, expr])

The result is canonical.

class ComputeEngineiterationLimit: number  read only

experimental

class ComputeEnginejsonSerializationOptions

get jsonSerializationOptions(): JsonSerializationOptions
set jsonSerializationOptions(Partial<JsonSerializationOptions>)

class ComputeEnginelatexOptions

class ComputeEnginemul()

mul(ops: BoxedExpression[], metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Multiply"...)

The result is canonical.

class ComputeEnginenegate()

negate(expr: BoxedExpression, metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Negate", [expr])

The result is canonical.

class ComputeEnginenumber()

number(value, metadata?)
value:
  • | number
  • | MathJsonNumber
  • | Decimal
  • | Complex
  • | [num: number, denom: number]
metadata?: Metadata
BoxedExpression

Return a canonical boxed number

class ComputeEnginenumericMode: NumericMode

The numeric evaluation mode:

  • auto: use machine number if precision is 15 or less, allow complex numbers.
  • machine: 64-bit float, IEEE 754-2008, 64-bit float, 52-bit mantissa, about 15 digits of precision
  • decimal: arbitrary precision floating point numbers, as provided by the “decimal.js” library
  • complex: complex number represented by two machine numbers, a real and an imaginary part, as provided by the “complex.js” library

class ComputeEnginepair()

pair(first: BoxedExpression, second: BoxedExpression, metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Pair"...)

The result is canonical.

class ComputeEngineparse()

parse(s: string): BoxedExpression

Parse a string of LaTeX and return a corresponding BoxedExpression.

The result may not be canonical.


parse(s: null): null

parse(s: null | string): null | BoxedExpression

class ComputeEnginepattern()

class ComputeEnginepopScope()

popScope(): void

Remove the topmost scope from the scope stack.

class ComputeEnginepower()

power(base, exponent, metadata?)
base: BoxedExpression
exponent:
metadata?: Metadata
BoxedExpression

Shortcut for this.fn("Power"...)

The result is canonical.

class ComputeEngineprecision

get precision(): number
set precision(number | "machine")

The precision, or number of significant digits, for numeric calculations such as when calling ce.N().

To make calculations using more digits, at the cost of expended memory usage and slower computations, set the precision higher.

Trigonometric operations are accurate for precision up to 1,000.

class ComputeEnginepushScope()

pushScope(options?)
options?:
assumptions: Expression[];
dictionary: Readonly<Dictionary> | Readonly<Dictionary>[];
scope: Partial<Scope>;

Create a new scope and add it to the top of the scope stack

The options.scope property can be used to specify custom precision, etc… for this scope

class ComputeEnginerecursionLimit: number  read only

experimental

class ComputeEnginerules()

rules(rules: Rule[]): BoxedRuleSet

class ComputeEngineserialize()

serialize(x: Expression | BoxedExpression): string

Serialize a BoxedExpression or a MathJSON expression to a LaTeX string

class ComputeEnginesignal()

signal(expr: BoxedExpression, msg: string, code?: SignalMessage): void

Call this function if an unexpected condition occurs during execution of a function in the engine.

An ErrorSignal is a problem that cannot be recovered from.

A WarningSignal indicates a minor problem that does not prevent the execution to continue.


signal(sig: WarningSignal): void

class ComputeEnginestats: ComputeEngineStats  read only

class ComputeEnginestring()

string(s: string, metadata?: Metadata): BoxedExpression

Return a canonical boxed string

class ComputeEnginesymbol()

symbol(sym: string, metadata?: Metadata): BoxedExpression

Return a canonical boxed symbol

class ComputeEnginetimeLimit: number  read only

experimental

class ComputeEnginetolerance: number

Values smaller than the tolerance are considered to be zero for the purpose of comparison, i.e. if |b - a| <= tolerance, b is considered equal to a.

class ComputeEnginetuple()

tuple(elements: BoxedExpression[], metadata?: Metadata): BoxedExpression

Shortcut for this.fn("Tuple"...)

The result is canonical.

interface ComputeEngineStats

expressions: null | Set<BoxedExpression>
highwaterMark: number
symbols: Set<BoxedExpression>

interface Domain

Domains can be defined as a union or intersection of domains:

  • ["Union", "Number", "Boolean"] A number or a boolean.
  • ["SetMinus", "Number", 1] Any number except “1”.

interface DomainProperties / Methods

Dictionary Expression

Expression Properties

Function Expression

Numeric Expression

String Expression

Symbol Expression

Other

Object Methods

Relational Operator

interface Domaincodomain: null | Domain

interface DomaindomainExpression: DomainExpression

interface DomainisBoolean: boolean

interface DomainisFunction: boolean

interface DomainisLogicOperator: boolean

If true, when all the arguments are boolean, the result of the evaluation is a boolean. Boolean is any value with a domain of MaybeBoolean.

Example of logic functions: And, Or, Not, Implies

Default: false

interface DomainisNothing: boolean

interface DomainisNumeric: boolean

interface DomainisNumericFunction: boolean

If true, when all the arguments are numeric, the result of the evaluation is numeric. Numeric is any value with a domain of Number.

Example of numeric functions: Add, Multiply, Power, Abs

Default: false

interface DomainisPredicate: boolean

interface DomainisRealFunction: boolean

interface DomainisRelationalOperator: boolean

The function represent a relation between the first argument and the second argument, and evaluates to a boolean indicating if the relation is satisfied.

For example, Equal, Less, Approx, etc…

Default: false

Dictionary Expression

Expression Properties

Function Expression

Numeric Expression

String Expression

Symbol Expression

Other

interface Domainis()

is(s: BoxedExpression): boolean

From Object.is(). Equivalent to BoxedExpression.isSame()

interface DomainisMemberOf()

isMemberOf(expr: BoxedExpression): boolean

interface DomainisSubdomainOf()

isSubdomainOf(dom: string | Domain): boolean

Object Methods

Relational Operator

interface ExpressionMapInterface

[iterator](): IterableIterator<[BoxedExpression, U]>
clear(): void
delete(expr: BoxedExpression): void
get(expr: BoxedExpression): undefined | U
has(expr: BoxedExpression): boolean
set(expr: BoxedExpression, value: U): void

class LatexSyntax

To customize the parsing and serializing of LaTeX syntax, create a LatexSyntax instance.

class LatexSyntaxnew LatexSyntax()

new LatexSyntax(options?: NumberFormattingOptions & ParseLatexOptions & SerializeLatexOptions & {dictionary: LatexDictionary; onError: WarningSignalHandler}): LatexSyntax

class LatexSyntaxMethods / Properties

class LatexSyntaxgetDictionary()

getDictionary(domain?: DictionaryCategory | "all"): readonly LatexDictionaryEntry[]

Return a LaTeX dictionary suitable for the specified category, or "all" for all categories ("arithmetic", "algebra", etc…).

A LaTeX dictionary is needed to translate between LaTeX and MathJSON.

Each entry in the dictionary indicate how a LaTeX token (or string of tokens) should be parsed into a MathJSON expression.

For example an entry can define that the \pi LaTeX token should map to the symbol "Pi", or that the token - should map to the function ["Negate",...] when in a prefix position and to the function ["Subtract", ...] when in an infix position.

Furthermore, the information in each dictionary entry is used to serialize the LaTeX string corresponding to a MathJSON expression.

Use the value returned by this function to the options argument of the constructor.

class LatexSyntaxparse()

parse(latex: string): Expression

class LatexSyntaxserialize()

serialize(expr: Expression): string

interface Parser

interface ParserProperties / Methods

interface ParserapplyInvisibleOperator()

applyInvisibleOperator(terminator: Terminator, lhs: null | Expression): null | Expression

interface ParseratEnd: boolean

True if the last token has been reached

interface ParseratTerminator()

atTerminator(t: Terminator): boolean

Return true if the terminator condition is met

interface ParsercomputeEngine: IComputeEngine

interface Parserindex: number

interface ParserlatexAfter()

latexAfter(): string

Return a LaTeX string after the index

interface ParserlatexBefore()

latexBefore(): string

Return a LaTeX string before the index

interface ParserlookAhead()

lookAhead(): string[]

Return an array of string corresponding to tokens ahead. The index is unchanged.

interface Parsermatch()

match(tokens: string): boolean

If the next token matches the target advance and return true. Otherwise return false

interface ParsermatchAll()

matchAll(tokens: string | string[]): boolean

interface ParsermatchAny()

matchAny(tokens: string[]): string

interface ParsermatchArguments()

matchArguments(kind: "" | "group" | "implicit" | "enclosure"): null | Expression[]
  • ‘enclosure’ : will look for an argument inside an enclosure (an open/close fence)
  • ‘group’: arguments follow directly the symbol, until an end of group token <}>
  • ‘implicit’: either an expression inside a pair of (), or just a primary (i.e. we interpret \cos x + 1 as \cos(x) + 1)

interface ParsermatchChar()

matchChar(): null | string

If the next token is a character, return it and advance the index This includes plain characters (e.g. ‘a’, ‘+’…), characters defined in hex (^^ and ^^^^), the \char and \unicode command.

interface ParsermatchColor()

matchColor(background?: boolean): null | string

Return a CSS color. Handle the various color formats supported by the xcolor package.

interface ParsermatchDecimalDigits()

matchDecimalDigits(): string

interface ParsermatchExponent()

matchExponent(): string

interface ParsermatchExpression()

matchExpression(until?: Partial<Terminator>): null | Expression

Parse an expression:

<expression> ::=
 | <prefix-op> <expression>
 | <primary>
 | <primary> <infix-op> <expression>

This is the top-level parsing entry point.

Stop when an operator of precedence less than until.minPrec or the sequence of tokens until.tokens is encountered

until is { minPrec:0 } by default.

interface ParsermatchLatexDimension()

matchLatexDimension(): null | string

Return a LaTeX dimension.

interface ParsermatchMiddleDelimiter()

matchMiddleDelimiter(delimiter: string): boolean

interface ParsermatchNumber()

matchNumber(): string

interface ParsermatchOpenDelimiter()

matchOpenDelimiter(openDelim: Delimiter, closeDelim: Delimiter): null | string[]

If matches the normalized open delimiter, returns the expected closing delimiter.

For example, if openDelim is (, and closeDelim is ) it would match \left\lparen and return ['\right', '\rparen'], which can be matched with matchAll()

interface ParsermatchOptionalLatexArgument()

matchOptionalLatexArgument(): null | Expression

If the next tokens correspond to an optional LaTeX argument, enclosed with [ and ] return the content of the argument as an expression and advance the index past the closing ].

Otherwise, return null.

interface ParsermatchPrimary()

matchPrimary(): null | Expression
   <primary> :=
      (<number> | <symbol> | <latex-command> | <function-call> | <matchfix-expr>)
      (<subsup> | <postfix-operator>)*
   <matchfix-expr> :=
       <matchfix-op-open> <expression> <matchfix-op-close>
   <function-call> ::=
     | <function><matchfix-op-group-open><expression>[',' <expression>]<matchfix-op-group-close>

If not a primary, return null and do not advance the index.

interface ParsermatchRequiredLatexArgument()

matchRequiredLatexArgument(): null | Expression

interface ParsermatchSign()

matchSign(): string

If the next token matches a + or - sign, return it and advance the index. Otherwise return '' and do not advance

interface ParsermatchSignedInteger()

matchSignedInteger(): string

interface ParsermatchSupsub()

matchSupsub(lhs: null | Expression): null | Expression

interface ParsermatchTabular()

matchTabular(endName: string): null | Expression

Parse a tabular environment, until \end{endName}

interface ParsermatchWhile()

matchWhile(tokens: string[]): string[]

interface Parsernext()

next(): string

Return the next token and advance the index

interface ParseronError: WarningSignalHandler

interface Parseroptions: Required<ParseLatexOptions>

interface Parserpeek: string

Return the next token, without advancing the index

interface ParserskipSpace()

skipSpace(): boolean

If there are any space, advance the index until a non-space is encountered

interface Pattern

interface PatternProperties / Methods

Dictionary Expression

Expression Properties

Function Expression

Numeric Expression

String Expression

Symbol Expression

Other

Object Methods

Relational Operator

Dictionary Expression

Expression Properties

Function Expression

Numeric Expression

String Expression

Symbol Expression

Other

interface Patterncount()

count(exprs: Iterable<BoxedExpression>, options?: PatternMatchOption): number

Return the number of exprs that matched the pattern

interface Patternmatch()

match(expr: BoxedExpression, options?: PatternMatchOption): null | Substitution

If expr does not match the pattern, return null.

Otherwise, return a substitution describing the values that the named wildcard in the pattern should be changed to in order for the pattern to be equal to the expression. If there are no named wildcards and the expression matches the pattern, and empty object literal {} is returned.

interface Patternsubs()

subs(sub: Substitution): Pattern

Replace all the symbols in the expression as indicated.

Note the same effect can be achieved with this.replace(), but using this.subs() is more efficient, and simpler.

interface Patterntest()

test(expr: BoxedExpression, options?: PatternMatchOption): boolean

If expr matches the pattern, return true, otherwise false

Object Methods

Relational Operator

interface Serializer

interface SerializerProperties / Methods

interface SerializerapplyFunctionStyle()

applyFunctionStyle(expr: Expression, level: number): "paren" | "leftright" | "big" | "none"

Styles

interface SerializerfractionStyle()

fractionStyle(expr: Expression, level: number): "quotient" | "inline-solidus" | "nice-solidus" | "reciprocal" | "factor"

interface SerializergroupStyle()

groupStyle(expr: Expression, level: number): "paren" | "leftright" | "big" | "none"

interface Serializerlevel: number

“depth” of the expression:

  • 0 for the root
  • 1 for the arguments of the root
  • 2 for the arguments of the arguments of the root
  • etc…

This allows for variation of the LaTeX serialized based on the depth of the expression, for example using \Bigl( for the top level, and \bigl( or ( for others.

interface SerializerlogicStyle()

logicStyle(expr: Expression, level: number): "boolean" | "word" | "uppercase-word" | "punctuation"

interface SerializernumericSetStyle()

numericSetStyle(expr: Expression, level: number): "compact" | "regular" | "interval" | "set-builder"

interface SerializeronError: WarningSignalHandler

interface Serializeroptions: Required<SerializeLatexOptions>

interface SerializerpowerStyle()

powerStyle(expr: Expression, level: number): "quotient" | "solidus" | "root"

interface SerializerrootStyle()

rootStyle(expr: Expression, level: number): "radical" | "quotient" | "solidus"

interface Serializerserialize()

serialize(expr: null | Expression): string

Output a LaTeX string representing the expression

interface Serializerwrap()

wrap(expr: null | Expression, prec?: number): string

Add a group fence around the expression if it is an operator of precedence less than or equal to prec.

interface SerializerwrapShort()

wrapShort(expr: null | Expression): string

Add a group fence around the expression if it is short (not a function)

interface SerializerwrapString()

wrapString(s: string, style: "paren" | "leftright" | "big" | "none"): string

version

version: ""

module compute-engineTypes

AssumeResult

  • | "internal-error"
  • | "not-a-predicate"
  • | "contradiction"
  • | "tautology"
  • | "ok"

BaseDefinition

description: string | string[];

A short (about 1 line) description. May contain Markdown.

domain: Domain | DomainExpression | string | (ce: IComputeEngine, args: BoxedExpression[]): Domain | DomainExpression;

The domain of this item.

For dictionaries, this is the domain of all the items in the dictionary.

For strings, it’s always ‘String’.

For symbols, this is the domain of their value.

For functions, this is the signature of the function

When domain is a handler, calculate the domain (or signature) based on the arguments (for expressions others than functions, args is an empty array). If the function cannot be applied to the arguments, return null.

name: string;

The name of the symbol or function for this definition

The name of a symbol or function is an arbitrary string of Unicode characters, however the following conventions are recommended:

  • Use only letters, digits and -, and the first character should be a letter: /^[a-zA-Z][a-zA-Z0-9-]+/
  • Built-in functions and symbols should start with an uppercase letter
url: string;

A URL pointing to more information about this symbol or head.

wikidata: string;

A short string representing an entry in a wikibase.

For example Q167 is the wikidata entry for the Pi constant.

BaseEntry

Maps a string of LaTeX tokens to a function or symbol and vice-versa.


name: string;

Map a MathJSON function or symbol name to this entry.

Each entry should have at least a name or a parse handler.

An entry with no name cannot be serialized: the name is used to map a MathJSON function or symbol name to the appropriate entry for serializing. However, an entry with no name can be used to define a synonym (for example for the symbol \varnothing which is a synonym for \emptyset).

If not parse handler is provided, only the trigger is used to select this entry. Otherwise, if the trigger of the entry matches the current token, the parse handler is invoked.

serialize: LatexString | SerializeHandler;

Transform an expression into a LaTeX string. If no serialize handler is provided, the trigger property is used

trigger: LatexString | LatexToken[];

The trigger is the set of tokens that will make this record eligible for attempting to parse the stream and generate an expression. After the trigger matches, the parse handler is called, if available.

matchfix operators use openDelimiter and closeDelimiter instead.

BoxedBaseDefinition

description: string | string[];
domain: Domain | (ce: IComputeEngine, args: BoxedExpression[]): Domain | DomainExpression;
name: string;
scope: RuntimeScope | undefined;

The scope this definition belongs to.

This field is usually undefined, but its value is set by getDefinition()

url: string;
wikidata: string;
_purge: (): undefined;

BoxedFunctionDefinition

BoxedLambdaExpression

BoxedRule

[lhs: Pattern, rhs: BoxedExpression, priority: number, condition: undefined | (wildcards: Substitution): boolean]

BoxedRuleSet

CompiledExpression

evaluate?: (scope: {[symbol: string]: BoxedExpression}): number | BoxedExpression;

DefaultEntry

A simple LaTeX dictionary entry, for example for a command like \pi.


Delimiter

Open and close delimiters that can be used with MatchfixEntry record to define new LaTeX dictionary entries.


  • | ")"
  • | "("
  • | "]"
  • | "["
  • | "{"
  • | "}"
  • | "<"
  • | ">"
  • | "|"
  • | "||"
  • | "\lceil"
  • | "\rceil"
  • | "\lfloor"
  • | "\rfloor"

Dictionary

A dictionary contains definitions for symbols, functions and rules.


functions: FunctionDefinition[];
simplifyRules: BoxedRuleSet;
symbols: SymbolDefinition[];

DictionaryCategory

  • | "algebra"
  • | "arithmetic"
  • | "calculus"
  • | "collections"
  • | "combinatorics"
  • | "core"
  • | "dimensions"
  • | "domains"
  • | "linear-algebra"
  • | "logic"
  • | "numeric"
  • | "other"
  • | "physics"
  • | "polynomials"
  • | "relop"
  • | "sets"
  • | "statistics"
  • | "symbols"
  • | "trigonometry"
  • | "units"

DomainExpression

EnvironmentEntry

A LaTeX dictionary entry for an environment, that is a LaTeX construct using \begin{...}...\end{...}.


EnvironmentParseHandler

(parser: Parser, reqArgs: Expression[], optArgs: Expression[]): Expression | null

FunctionDefinition

Definition record for a function.


  • BaseDefinition &
  • Partial<FunctionDefinitionFlags> &
  • complexity: number;

    A number used to order arguments. Argument with higher complexity are placed after arguments with lower complexity when ordered canonically in commutative functions.

    • Additive functions: 1000-1999
    • Multiplicative functions: 2000-2999
    • Root and power functions: 3000-3999
    • Log functions: 4000-4999
    • Trigonometric functions: 5000-5999
    • Hypertrigonometric functions: 6000-6999
    • Special functions (factorial, Gamma, …): 7000-7999
    • Collections: 8000-8999
    • Inert and styling: 9000-9999
    • Logic: 10000-10999
    • Relational: 11000-11999

    Default: 100,000

    evaluate: LambdaExpression | (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression | undefined;

    Evaluate symbolically an expression.

    The arguments have been symbolically evaluated, except the arguments to which a hold apply.

    It is not necessary to further simplify or evaluate the arguments.

    If the expression cannot be evaluated, due to the values, domains, or assumptions about its arguments, for example, return undefined.

    hold: "none" | "all" | "first" | "rest" | "last" | "most";
    • none Each of the arguments is evaluated (default)
    • all None of the arguments are evaluated and they are passed as is
    • first The first argument is not evaluated, the others are
    • rest The first argument is evaluated, the others aren’t
    range: [min: number, max: number];

    The minimum and maximum values of the result of the function

    sequenceHold: boolean;

    If true, Sequence arguments appearing in the arguments of a function should not automatically be flattened out

    N?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;

    Evaluate numerically an expression.

    The arguments args have been simplified and evaluated, numerically if possible, except the arguments to which a hold apply.

    The arguments may be a combination of numbers, symbolic expressions and other expressions.

    Perform as many calculations as possible, and return the result.

    Return undefined if there isn’t enough information to perform the evaluation, for example one of the arguments is a symbol with no value. If the handler returns undefined, symbolic evaluation of the expression will be returned instead to the caller.

    Return NaN if there is enough information to perform the evaluation, but a literal argument is out of range or not of the expected type.

    Also return NaN if the result of the evaluation would be a complex number, but complex numbers are not allowed (the engine.numericMode is not complex or auto).

    If the ce.numericMode is auto or complex, you may return a Complex number as a result. Otherwise, if the result is a complex value, return NaN. If Complex are not allowed, none of the arguments will be complex literals.

    If the ce.numericMode is decimal or auto and this.engine.precision is > 15, you may return a Decimal number. Otherwise, return a machine number approximation. If Decimal are not allowed, none of the arguments will be Decimal literal.

    You may perform any necessary computations, including approximate calculations on floating point numbers.

    canonical?: (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression;

    Return the canonical form of the expression with the arguments args.

    All the arguments that are not subject to a hold are in canonical form. Any Nothing argument has been removed.

    If the function is associative, idempotent or an involution, it should handle its arguments accordingly. Notably, if it is commutative, the arguments should be sorted in canonical order.

    The handler can make transformations based on the value of the arguments that are literal and either rational numbers (i.e. arg.isLiteral && arg.isRational) or integers (i.e. isLiteral && arg.isInteger).

    The handler should not consider the value of the arguments that are symbols or functions.

    The handler should not consider any assumptions about any of the arguments that are symbols or functions i.e. arg.isZero, arg.isInteger, etc…

    The handler should not make transformations based on the value of floating point numbers.

    The result of the handler should be a canonical expression.

    compile?: (expr: BoxedExpression): CompiledExpression;

    Return a compiled (optimized) expression.

    evalDimension?: (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression;
    experimental

    Dimensional analysis

    sgn?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | 0 | 1 | -1;

    Return the sign of the function given a list of arguments.

    simplify?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;

    Rewrite an expression into a simpler form.

    The arguments are in canonical form and have been simplified.

    The handler can use the values assigned to symbols and the assumptions about symbols, for example with arg.machineValue, arg.isInteger or arg.isPositive.

    Even though a symbol may not have a value, there may be some information about it reflected for example in this.isZero or this.isPrime.

    The handler should not perform approximate numeric calculations, such as calculations involving floating point numbers. Making exact calculations on integers or rationals is OK. It is recommended, but not required, that the calculations be limited to this.smallIntegerValue (i.e. numeric representations of the expression as an integer of small magnitude).

    This handler should not have any side-effects: do not modify the environment of the ComputeEngine instance, do not perform I/O, do not do calculations that depend on random values.

    If no simplification can be performed due to the values, domains or assumptions about its arguments, for example, return undefined.

FunctionDefinitionFlags

A function definition can have some flags to indicate specific properties of the function.


associative: boolean;

If true, ["f", ["f", a], b] simplifies to ["f", a, b]

Default: false

commutative: boolean;

If true, ["f", a, b] equals ["f", b, a]. The canonical version of the function will order the arguments.

Default: false

idempotent: boolean;

If true, ["f", ["f", x]] simplifies to ["f", x].

Default: false

inert: boolean;

An inert function evaluates directly to one of its argument, typically the first one. They may be used to provide formating hints, but do not affect simplification or evaluation.

Default: false

involution: boolean;

If true, ["f", ["f", x]] simplifies to x.

Default: false

pure: boolean;

If true, the value of this function is always the same for a given set of arguments and it has no side effects.

An expression using this function is pure if the function and all its arguments are pure.

For example Sin is pure, Random isn’t.

This information may be used to cache the value of expressions.

Default: true

threadable: boolean;

If true, the function is applied element by element to lists, matrices and equations.

Default: false

InfixEntry

  • BaseEntry &
  • associativity: "right" | "left" | "non" | "both";
    • both: a + b + c +(a, b, c)
    • left: a / b / c -> /(/(a, b), c)
    • right: a = b = c -> =(a, =(b, c))
    • non: a < b < c -> syntax error
    • a both-associative operator has an unlimited number of arguments
    • a left, right or non associative operator has at most two arguments
    kind: "infix";

    Infix position, with an operand before and an operand after: a ⊛ b.

    Example: +, \times.

    parse: string | InfixParseHandler;
    precedence: number;

InfixParseHandler

(parser: Parser, until: Terminator, lhs: Expression): Expression | null

JsonSerializationOptions

Options to control the serialization to MathJSON when using BoxedExpression.json.


exclude: string[];

A list of space separated function names that should be excluded from the JSON output.

Those functions are replaced with an equivalent, for example, Square with Power, etc…

Possible values include Sqrt, Root, Square, Exp, Subtract, Rational, Complex

Default: [] (none)

metadata: ("all" | "wikidata" | "latex")[];

A list of space separated keywords indicating which metadata should be included in the MathJSON. If metadata is included, shorthand notation is not used.

Default: [] (none)

repeatingDecimal: boolean;

If true, repeating decimals are detected and serialized accordingly For example:

  • 1.3333333333333333 ( \to ) 1.(3)
  • 0.142857142857142857142857142857142857142857142857142 ( \to ) 0.(1428571)

Default: true

shorthands: ("all" | "number" | "symbol" | "function" | "dictionary" | "string")[];

A list of space separated keywords indicating which MathJSON expressions can use a shorthand.

Default: ['all']

LambdaExpression

LatexDictionary

LatexDictionaryEntry

LatexString

A LaTeX string starts and end with $, for example "$\frac{\pi}{2}$".


string

LatexToken

A LatexToken is a token as returned by Scanner.peek.

It can be one of the indicated tokens, or a string that starts with a \ for LaTeX commands, or a LaTeX character which includes digits, letters and punctuation.


  • | string
  • | "<{>"
  • | "<}>"
  • | "<space>"
  • | "<$>"
  • | "<$$>"

MatchfixEntry

  • BaseEntry &
  • closeDelimiter: Delimiter | LatexToken[];
    kind: "matchfix";
    openDelimiter: Delimiter | LatexToken[];

    If kind is 'matchfix': the closeDelimiter and openDelimiter property are required

    parse: MatchfixParseHandler;

    When invoked, the parser is pointing after the close delimiter. The argument of the handler is the body, i.e. the content between the open delimiter and the close delimiter.

MatchfixParseHandler

(parser: Parser, body: Expression): Expression | null

Metadata

Metadata that can be associated with a BoxedExpression


latex: string;
wikidata: string;

NumberFormattingOptions

avoidExponentsInRange: [negativeExponent: number, positiveExponent: number];
beginExponentMarker: LatexString;
beginRepeatingDigits: LatexString;
decimalMarker: LatexString;

A string representing the decimal marker, the string separating the whole portion of a number from the fractional portion, i.e. the ‘.’ in ‘3.1415’.

Some countries use a comma rather than a dot. In this case it is recommended to use "{,}" as the marker: the surrounding bracket ensure there is no additional gap after the comma.

Default: "."

endExponentMarker: LatexString;
endRepeatingDigits: LatexString;
exponentProduct: LatexString;
groupSeparator: LatexString;

A string representing the separator between groups of digits, used to improve readability of numbers with lots of digits.

If you change it to another value, be aware that this may lead to unexpected results. For example, if changing it to , the expression x_{1,2} will parse as x with a subscript of 1.2, rather than x with two subscripts, 1 and 2.

Default: "\\," (thin space, 3/18mu) (Resolution 7 of the 1948 CGPM)

imaginaryNumber: LatexString;
negativeInfinity: LatexString;
notANumber: LatexString;
notation: "engineering" | "auto" | "scientific";
positiveInfinity: LatexString;
precision: number;
truncationMarker: LatexString;

NumericMode

The numeric evaluation mode:

  • auto: use machine number if precision is 15 or less, allow complex numbers.
  • machine: 64-bit float, IEEE 754-2008, 64-bit float, 52-bit mantissa, about 15 digits of precision
  • decimal: arbitrary precision floating point numbers, as provided by the “decimal.js” library
  • complex: complex number represented by two machine numbers, a real and an imaginary part, as provided by the “complex.js” library

  • | "auto"
  • | "machine"
  • | "decimal"
  • | "complex"

ParametricDomain

ParametricDomainFunction

  • | "Function"
  • | "Union"
  • | "List"
  • | "Record"
  • | "Tuple"
  • | "Intersection"
  • | "Range"
  • | "Interval"
  • | "Optional"
  • | "Some"
  • | "Head"
  • | "Symbol"
  • | "Literal"

ParseHandler

ParseLatexOptions

applyInvisibleOperator: "auto" | null | (parser: Parser, lhs: Expression, rhs: Expression): Expression | null;

This function is invoked when a number is followed by a symbol, an open delimiter or a function.

If this function is set to null, the lhs and rhs are joined as a Sequence.

If this function is set to undefined it behaves in the following way:

  • a number followed by a numeric expression is considered as separated with an invisible multiplication sign, and the two are joined as [‘Multiply’, lhs, rhs].
  • a number followed by a rational number is considered to be separated with an invisible plus, and the two are joined as [‘Add’, lhs,

For example with 2\frac{3}{4}: ["Add", 2, ["Divide", 3, 4]]

parseArgumentsOfUnknownLatexCommands: boolean;

When an unknown LaTeX command is encountered, attempt to parse any arguments it may have.

For example, \foo{x+1} would produce ['\foo', ['Add', 'x', 1]] if this property is true, ['LatexSymbols', '\foo', '<{>', 'x', '+', 1, '<{>'] otherwise.

parseNumbers: boolean;

When a number is encountered, parse it.

Otherwise, return each token making up the number (minus sign, digits, decimal separator, etc…).

Default: true

preserveLatex: boolean;

If true, the expression will be decorated with the LaTeX fragments corresponding to each elements of the expression.

The top-level expression, that is the one returned by parse(), will include the verbatim LaTeX input that was parsed. The sub-expressions may contain a slightly different LaTeX, for example with consecutive spaces replaced by one, with comments removed and with some low-level LaTeX commands replaced, for example \egroup and \bgroup.

Default: false

skipSpace: boolean;

If true, ignore space characters.

Default: true

parseUnknownSymbol: (symbol: string, parser: Parser): "symbol" | "function" | "unknown";

This handler is invoked when the parser encounter a set of tokens at a position that could be a symbol or function.

The symbol argument is one or more tokens.

The handler can return:

  • symbol to indicate the string represent a constant or variable.

  • function to indicate the string is a function name. If an apply function operator (typically, parentheses) follow, parse them as arguments to the function.

  • error, an error condition is raised.

PatternMatchOption

exact: boolean;
numericTolerance: number;
recursive: boolean;

PostfixEntry

PostfixParseHandler

(parser: Parser, lhs: Expression): Expression | null

PrefixEntry

  • BaseEntry &
  • kind: "prefix";

    Prefix position, with an operand after: ⊛ a

    Example: -, \not.

    parse: PrefixParseHandler;
    precedence: number;

PrefixParseHandler

(parser: Parser, until: Terminator): Expression | null

ReplaceOptions

iterationLimit: number;

If iterationLimit > 1, the rules will be repeatedly applied until no rules apply, up to maxIterations times.

Note that if once is true, maxIterations has no effect.

Default: 1

once: boolean;

If true, stop after the first rule that matches.

If false, apply all the remaining rules even after the first match.

Default: true

recursive: boolean;

If true, apply replacement rules to all sub-expressions. If false, only consider the top-level expression.

Default: true

Rule

A rule describes how to modify an expressions that matches a lhs pattern into a new expressions matching rhs.

x-1 ( \to ) 1-x (x+1)(x-1) ( \to ) `x^2-1

The lhs can be expressed as a LaTeX string or a MathJSON expression.

Unbound variables (x, but not Pi) are matched structurally with a a target expression, then the expression is rewritten as the rhs, with the corresponding unbound variables in the rhs replaced by their values in the `lhs.

Pattern symbols (e.g. _1, _a) can be used as well.

In addition:

  • __1 (__a, etc…) match a sequence of one or more expressions
  • ___1 (___a, etc…) match a sequence of zero or more expressions

[lhs: LatexString | SemiBoxedExpression | Pattern, rhs: LatexString | SemiBoxedExpression, options: {condition: LatexString | (wildcards: Substitution): boolean; priority: number}]

RuntimeDictionary

The entries of a CompiledDictionary have been validated and optimized for faster evaluation.

When a new scope is created with pushScope() or when creating a new engine instance, new instances of RuntimeDictionary are created as needed.


functionWikidata: Map<string, BoxedFunctionDefinition>;
functions: Map<string, BoxedFunctionDefinition[]>;
symbolWikidata: Map<string, BoxedSymbolDefinition>;
symbols: Map<string, BoxedSymbolDefinition>;

RuntimeScope

  • Scope &
  • assumptions: undefined | ExpressionMapInterface<boolean>;
    dictionary: RuntimeDictionary;
    lowWaterMark: number;

    Free memory should not go below this level for execution to proceed

    origin: {column: number; line: number; name: string};

    The location of the call site that created this scope

    parentScope: RuntimeScope;
    warnings: WarningSignal[];

    Set when one or more warnings have been signaled in this scope

Scope

A scope is a set of names in a dictionary that are bound (defined) in a MathJSON expression.

Scopes are arranged in a stack structure. When an expression that defined a new scope is evaluated, the new scope is added to the scope stack. Outside of the expression, the scope is removed from the scope stack.

The scope stack is used to resolve symbols, and it is possible for a scope to ‘mask’ definitions from previous scopes.

Scopes are lexical (also called a static scope): they are defined based on where they are in an expression, they are not determined at runtime.


iterationLimit: number;
experimental

Signal iteration-limit-exceeded when the iteration limit for this scope is exceeded. Default: no limits.

memoryLimit: number;
experimental

Signal out-of-memory when the memory usage for this scope is exceeded. Memory in Megabytes, default: 1Mb.

recursionLimit: number;
experimental

Signal recursion-depth-exceeded when the recursion depth for this scope is exceeded.

timeLimit: number;
experimental

Signal timeout when the execution time for this scope is exceeded. Time in seconds, default 2s.

warn: WarningSignalHandler;

This handler is invoked when exiting this scope if there are any warnings pending.

SemiBoxedExpression

A semi boxed expression is an MathJSON expression which can include some boxed terms.

This is convenient when creating new expressions from portions of an existing BoxedExpression while avoiding unboxing and reboxing.


  • | BoxedExpression
  • | number
  • | Decimal
  • | Complex
  • | MathJsonNumber
  • | MathJsonString
  • | MathJsonSymbol
  • | string
  • | MathJsonFunction
  • | MathJsonDictionary
  • | SemiBoxedExpression[]

SerializeHandler

(serializer: Serializer, expr: Expression): string

SerializeLatexOptions

invisibleMultiply: LatexString;

LaTeX string used to render an invisible multiply, e.g. in ‘2x’. Leave it empty to join the adjacent terms, or use \cdot to insert a \cdot operator between them, i.e. 2\cdot x.

Empty by default.

invisiblePlus: LatexString;

LaTeX string used for an invisible plus, e.g. in ‘1 3/4’. Leave it empty to join the main number and the fraction, i.e. render it as 1\frac{3}{4}, or use + to insert a + operator between them, i.e. 1+\frac{3}{4}

Empty by default.

missingSymbol: LatexString;

When an expression contains the symbol Missing, serialize it with this LaTeX string

multiply: LatexString;

LaTeX string used for an explicit multiply operator,

Default: \times

applyFunctionStyle: (expr: Expression, level: number): "paren" | "leftright" | "big" | "none";
fractionStyle: (expr: Expression, level: number): "quotient" | "inline-solidus" | "nice-solidus" | "reciprocal" | "factor";
groupStyle: (expr: Expression, level: number): "paren" | "leftright" | "big" | "none";
logicStyle: (expr: Expression, level: number): "boolean" | "word" | "uppercase-word" | "punctuation";
numericSetStyle: (expr: Expression, level: number): "compact" | "regular" | "interval" | "set-builder";
powerStyle: (expr: Expression, level: number): "quotient" | "solidus" | "root";
rootStyle: (expr: Expression, level: number): "radical" | "quotient" | "solidus";

SimplifyOptions

Options for BoxedExpression.simplify()


Substitution

A substitution describes the values of the wildcards in a pattern so that the pattern is equal to a target expression.

A substitution can also be considered a more constrained version of a rule whose lhs is always a symbol.


[symbol: string]: BoxedExpression}

SymbolDefinition

A bound symbol (i.e. one with an associated definition) has either a domain (e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14… domain = TranscendentalNumber)


SymbolDefinitionFlags

constant: boolean;

If true the value of the symbol is constant.

If false, the symbol is a variable.

hold: boolean;

If false, the value of the symbol is substituted during canonicalization or simplification.

If true, the value is only replaced during a ce.N() or ce.evaluate().

Default: true

SymbolEntry

  • BaseEntry &
  • kind: "symbol";
    optionalLatexArg: number;

    If a LaTeX command (i.e. the trigger starts with \, e.g. \sqrt) indicates the number of optional arguments expected (indicate with square brackets).

    For example, for the \sqrt command, 1: \sqrt[3]{x}

    parse: Expression | SymbolParseHandler;
    precedence: number;

    Used for appropriate wrapping (i.e. when to surround it with parens)

    requiredLatexArg: number;

    If a LaTeX command (i.e. the trigger starts with \, e.g. \frac) indicates the number of required arguments expected (indicated with curly braces).

    For example, for the \frac command, 2: \frac{1}{n}

SymbolFlags

When used in a SymbolDefinition, these flags are optional.

If provided, they will override the value derived from the symbol’s value.

For example, it might be useful to override algebraic = false for a transcendental number.


NaN: boolean | undefined;
algebraic: boolean | undefined;
complex: boolean | undefined;
composite: boolean | undefined;
even: boolean | undefined;
extendedComplex: boolean | undefined;
extendedReal: boolean | undefined;
finite: boolean | undefined;
imaginary: boolean | undefined;
infinity: boolean | undefined;
integer: boolean | undefined;
negative: boolean | undefined;
negativeOne: boolean | undefined;
nonNegative: boolean | undefined;
nonPositive: boolean | undefined;
notZero: boolean | undefined;
number: boolean | undefined;
odd: boolean | undefined;
one: boolean | undefined;
positive: boolean | undefined;
prime: boolean | undefined;
rational: boolean | undefined;
real: boolean | undefined;
zero: boolean | undefined;

SymbolParseHandler

(parser: Parser): Expression | null

Terminator

This indicates a condition under which parsing should stop:

  • a specific string of tokens has been encountered
  • an operator of a precedence higher than specified has been encountered
  • the last token has been reached
  • or if a function is provided, the function returns true;

minPrec: number;
tokens: LatexToken[];
condition?: (parser: Parser): boolean;

module compute-engineFunctions

getVars()

getVars(expr: BoxedExpression): string[]

Return the free symbols in the expression, recursively. A variable, or free symbol,is a symbol that is not bound to a value.

Documentation built with grok