@cortex-js/compute-engine 0.86.1 → 0.86.2
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.
- package/CHANGELOG.md +40 -0
- package/dist/esm-min/chunks/{chunk-RF2RDYMF.js → chunk-7WM7O5R7.js} +30 -30
- package/dist/esm-min/chunks/{chunk-JBEE4TIQ.js → chunk-S6GEG7AN.js} +1 -1
- package/dist/esm-min/compile.js +14 -14
- package/dist/esm-min/compute-engine.js +2 -2
- package/dist/esm-min/core.js +14 -14
- package/dist/esm-min/cortex.js +3 -3
- package/dist/esm-min/identities.js +2 -2
- package/dist/esm-min/integration-rules.js +3 -3
- package/dist/esm-min/interval.js +2 -2
- package/dist/esm-min/latex-syntax.js +2 -2
- package/dist/esm-min/math-json.js +2 -2
- package/dist/esm-min/numerics.js +2 -2
- package/dist/types/big-decimal/big-decimal.d.ts +1 -1
- package/dist/types/big-decimal/index.d.ts +1 -1
- package/dist/types/big-decimal/transcendentals.d.ts +1 -1
- package/dist/types/big-decimal/utils.d.ts +1 -1
- package/dist/types/common/ansi-codes.d.ts +1 -1
- package/dist/types/common/configuration-change.d.ts +1 -1
- package/dist/types/common/debug.d.ts +1 -1
- package/dist/types/common/fuzzy-string-match.d.ts +1 -1
- package/dist/types/common/grapheme-splitter.d.ts +1 -1
- package/dist/types/common/interruptible.d.ts +1 -1
- package/dist/types/common/one-of.d.ts +1 -1
- package/dist/types/common/signals.d.ts +1 -1
- package/dist/types/common/styled-text.d.ts +1 -1
- package/dist/types/common/terminal.d.ts +1 -1
- package/dist/types/common/type/ast-nodes.d.ts +1 -1
- package/dist/types/common/type/boxed-type.d.ts +1 -1
- package/dist/types/common/type/lexer.d.ts +1 -1
- package/dist/types/common/type/parse.d.ts +1 -1
- package/dist/types/common/type/parser.d.ts +1 -1
- package/dist/types/common/type/primitive.d.ts +1 -1
- package/dist/types/common/type/reduce.d.ts +1 -1
- package/dist/types/common/type/serialize.d.ts +1 -1
- package/dist/types/common/type/subtype.d.ts +1 -1
- package/dist/types/common/type/type-builder.d.ts +1 -1
- package/dist/types/common/type/types.d.ts +1 -1
- package/dist/types/common/type/utils.d.ts +1 -1
- package/dist/types/common/utils.d.ts +1 -1
- package/dist/types/compile.d.ts +1 -1
- package/dist/types/compute-engine/assume.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/abstract-boxed-expression.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/apply.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/arithmetic-add.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/arithmetic-mul-div.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/arithmetic-power.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/ascii-math.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/box.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-dictionary.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-function.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-number.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-operator-definition.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-patterns.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-string.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-symbol.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-tensor.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/boxed-value-definition.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/cache.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/canonical-utils.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/canonical.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/compare.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/conditional-value.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/constants.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/constraint-subject.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/diophantine.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/exp-to-trig.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/expand.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/explain-labels.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/explain.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/expression-map.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/factor.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/flatten.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/function-literal.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/hold.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/inequality-bounds.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/init-lazy-refs.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/invisible-operator.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/match-dispatch.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/match.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/modular-arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/multivariate-gcd.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/multivariate-poly.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/negate.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/numerics.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/order.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/pattern-utils.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/polynomial-degree.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/polynomials.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/predicates.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/rule-index.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/rules.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/serialize.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/sgn.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/simplify.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/solve-congruence.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/solve-domain.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/solve-linear-system.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/solve-system.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/solve.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/stochastic-equal.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/trigonometry.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/type-guards.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/utils.d.ts +1 -1
- package/dist/types/compute-engine/boxed-expression/validate.d.ts +1 -1
- package/dist/types/compute-engine/collection-utils.d.ts +1 -1
- package/dist/types/compute-engine/compilation/angular-unit.d.ts +1 -1
- package/dist/types/compute-engine/compilation/base-compiler.d.ts +18 -1
- package/dist/types/compute-engine/compilation/compile-expression.d.ts +1 -1
- package/dist/types/compute-engine/compilation/constant-folding.d.ts +1 -1
- package/dist/types/compute-engine/compilation/glsl-target.d.ts +1 -1
- package/dist/types/compute-engine/compilation/gpu-target.d.ts +1 -1
- package/dist/types/compute-engine/compilation/interval-javascript-target.d.ts +1 -1
- package/dist/types/compute-engine/compilation/javascript-target.d.ts +1 -1
- package/dist/types/compute-engine/compilation/python-target.d.ts +1 -1
- package/dist/types/compute-engine/compilation/types.d.ts +1 -1
- package/dist/types/compute-engine/compilation/wgsl-target.d.ts +1 -1
- package/dist/types/compute-engine/cost-function.d.ts +1 -1
- package/dist/types/compute-engine/differential-equation-utils.d.ts +1 -1
- package/dist/types/compute-engine/engine-assumptions.d.ts +1 -1
- package/dist/types/compute-engine/engine-cache.d.ts +1 -1
- package/dist/types/compute-engine/engine-common-symbols.d.ts +1 -1
- package/dist/types/compute-engine/engine-compilation-targets.d.ts +1 -1
- package/dist/types/compute-engine/engine-configuration-lifecycle.d.ts +1 -1
- package/dist/types/compute-engine/engine-declarations.d.ts +1 -1
- package/dist/types/compute-engine/engine-expression-entrypoints.d.ts +1 -1
- package/dist/types/compute-engine/engine-extension-contracts.d.ts +1 -1
- package/dist/types/compute-engine/engine-library-bootstrap.d.ts +1 -1
- package/dist/types/compute-engine/engine-numeric-configuration.d.ts +1 -1
- package/dist/types/compute-engine/engine-runtime-state.d.ts +1 -1
- package/dist/types/compute-engine/engine-scope.d.ts +1 -1
- package/dist/types/compute-engine/engine-sequences.d.ts +1 -1
- package/dist/types/compute-engine/engine-simplification-rules.d.ts +1 -1
- package/dist/types/compute-engine/engine-startup-coordinator.d.ts +1 -1
- package/dist/types/compute-engine/engine-type-resolver.d.ts +1 -1
- package/dist/types/compute-engine/engine-validation-entrypoints.d.ts +1 -1
- package/dist/types/compute-engine/free-functions.d.ts +1 -1
- package/dist/types/compute-engine/function-properties/index.d.ts +1 -1
- package/dist/types/compute-engine/function-utils.d.ts +1 -1
- package/dist/types/compute-engine/fungrim/loader.d.ts +1 -1
- package/dist/types/compute-engine/fungrim/types.d.ts +1 -1
- package/dist/types/compute-engine/global-types.d.ts +1 -1
- package/dist/types/compute-engine/index.d.ts +1 -1
- package/dist/types/compute-engine/interpret-oeis.d.ts +1 -1
- package/dist/types/compute-engine/interval/arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/interval/comparison.d.ts +1 -1
- package/dist/types/compute-engine/interval/elementary.d.ts +1 -1
- package/dist/types/compute-engine/interval/index.d.ts +1 -1
- package/dist/types/compute-engine/interval/trigonometric.d.ts +1 -1
- package/dist/types/compute-engine/interval/types.d.ts +1 -1
- package/dist/types/compute-engine/interval/util.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/default-dictionary.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-algebra.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-calculus.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-colors.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-complex.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-core.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-linear-algebra.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-logic.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-other.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-relational-operators.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-sets.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-statistics.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-symbols.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-trigonometry.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions-units.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/definitions.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/dictionary/indexed-types.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/latex-syntax.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/parse-number.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/parse-symbol.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/parse.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/serialize-dms.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/serialize-number.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/serializer-style.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/serializer.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/tokenizer.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/types.d.ts +1 -1
- package/dist/types/compute-engine/latex-syntax/utils.d.ts +1 -1
- package/dist/types/compute-engine/library/arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/library/calculus.d.ts +1 -1
- package/dist/types/compute-engine/library/collections.d.ts +1 -1
- package/dist/types/compute-engine/library/colors.d.ts +1 -1
- package/dist/types/compute-engine/library/combinatorics.d.ts +1 -1
- package/dist/types/compute-engine/library/complex.d.ts +1 -1
- package/dist/types/compute-engine/library/control-structures.d.ts +1 -1
- package/dist/types/compute-engine/library/core.d.ts +1 -1
- package/dist/types/compute-engine/library/distributions.d.ts +1 -1
- package/dist/types/compute-engine/library/fractals.d.ts +1 -1
- package/dist/types/compute-engine/library/library.d.ts +1 -1
- package/dist/types/compute-engine/library/linear-algebra.d.ts +1 -1
- package/dist/types/compute-engine/library/logic-analysis.d.ts +1 -1
- package/dist/types/compute-engine/library/logic.d.ts +1 -1
- package/dist/types/compute-engine/library/measurement-arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/library/number-theory.d.ts +1 -1
- package/dist/types/compute-engine/library/polynomials.d.ts +1 -1
- package/dist/types/compute-engine/library/quantity-arithmetic.d.ts +1 -1
- package/dist/types/compute-engine/library/random-expression.d.ts +1 -1
- package/dist/types/compute-engine/library/relational-operator.d.ts +1 -1
- package/dist/types/compute-engine/library/sets.d.ts +1 -1
- package/dist/types/compute-engine/library/special-functions.d.ts +1 -1
- package/dist/types/compute-engine/library/statistics.d.ts +1 -1
- package/dist/types/compute-engine/library/trigonometry.d.ts +1 -1
- package/dist/types/compute-engine/library/type-handlers.d.ts +1 -1
- package/dist/types/compute-engine/library/unit-data.d.ts +1 -1
- package/dist/types/compute-engine/library/units.d.ts +1 -1
- package/dist/types/compute-engine/library/utils.d.ts +1 -1
- package/dist/types/compute-engine/numeric-value/big-numeric-value.d.ts +1 -1
- package/dist/types/compute-engine/numeric-value/exact-numeric-value.d.ts +1 -1
- package/dist/types/compute-engine/numeric-value/machine-numeric-value.d.ts +1 -1
- package/dist/types/compute-engine/numeric-value/types.d.ts +1 -1
- package/dist/types/compute-engine/numerics/bernoulli.d.ts +1 -1
- package/dist/types/compute-engine/numerics/bigint.d.ts +1 -1
- package/dist/types/compute-engine/numerics/complex-esm-augment.d.ts +1 -1
- package/dist/types/compute-engine/numerics/differential-equations.d.ts +1 -1
- package/dist/types/compute-engine/numerics/diophantine.d.ts +1 -1
- package/dist/types/compute-engine/numerics/distributions.d.ts +1 -1
- package/dist/types/compute-engine/numerics/expression.d.ts +1 -1
- package/dist/types/compute-engine/numerics/gauss-kronrod.d.ts +1 -1
- package/dist/types/compute-engine/numerics/interval.d.ts +1 -1
- package/dist/types/compute-engine/numerics/linear-algebra.d.ts +1 -1
- package/dist/types/compute-engine/numerics/monte-carlo.d.ts +1 -1
- package/dist/types/compute-engine/numerics/numeric-bigint.d.ts +1 -1
- package/dist/types/compute-engine/numerics/numeric-bignum.d.ts +1 -1
- package/dist/types/compute-engine/numerics/numeric-complex.d.ts +1 -1
- package/dist/types/compute-engine/numerics/numeric.d.ts +1 -1
- package/dist/types/compute-engine/numerics/oscillatory-quadrature.d.ts +1 -1
- package/dist/types/compute-engine/numerics/polynomial-roots.d.ts +1 -1
- package/dist/types/compute-engine/numerics/primes.d.ts +1 -1
- package/dist/types/compute-engine/numerics/random.d.ts +1 -1
- package/dist/types/compute-engine/numerics/rationals.d.ts +1 -1
- package/dist/types/compute-engine/numerics/richardson.d.ts +1 -1
- package/dist/types/compute-engine/numerics/special-functions.d.ts +1 -1
- package/dist/types/compute-engine/numerics/statistics.d.ts +1 -1
- package/dist/types/compute-engine/numerics/strings.d.ts +1 -1
- package/dist/types/compute-engine/numerics/types.d.ts +1 -1
- package/dist/types/compute-engine/numerics/unit-data.d.ts +1 -1
- package/dist/types/compute-engine/oeis.d.ts +1 -1
- package/dist/types/compute-engine/rubi/compile.d.ts +1 -1
- package/dist/types/compute-engine/rubi/driver.d.ts +1 -1
- package/dist/types/compute-engine/rubi/explain-trace.d.ts +1 -1
- package/dist/types/compute-engine/rubi/loader.d.ts +1 -1
- package/dist/types/compute-engine/rubi/match.d.ts +1 -1
- package/dist/types/compute-engine/rubi/normal-form.d.ts +1 -1
- package/dist/types/compute-engine/rubi/rubi-utils.d.ts +1 -1
- package/dist/types/compute-engine/rubi/types.d.ts +1 -1
- package/dist/types/compute-engine/sequence.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/antiderivative.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/derivative.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/differential-equations.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/distribute.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/explain-derivative.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/fu-cost.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/fu-transforms.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/fu.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/interpret.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/limit.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/logic-utils.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/recurrences.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/residue.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/series.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-abs.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-divide.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-factorial.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-hyperbolic.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-infinity.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-log.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-logic.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-power.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-product.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-rules.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-sum.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/simplify-trig.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/solver-utils.d.ts +1 -1
- package/dist/types/compute-engine/symbolic/trig-rewrite.d.ts +1 -1
- package/dist/types/compute-engine/tensor/tensor-fields.d.ts +1 -1
- package/dist/types/compute-engine/tensor/tensors.d.ts +1 -1
- package/dist/types/compute-engine/types-definitions.d.ts +1 -1
- package/dist/types/compute-engine/types-engine.d.ts +1 -1
- package/dist/types/compute-engine/types-evaluation.d.ts +1 -1
- package/dist/types/compute-engine/types-expression.d.ts +1 -1
- package/dist/types/compute-engine/types-kernel-evaluation.d.ts +1 -1
- package/dist/types/compute-engine/types-kernel-serialization.d.ts +1 -1
- package/dist/types/compute-engine/types-serialization.d.ts +1 -1
- package/dist/types/compute-engine/types.d.ts +1 -1
- package/dist/types/compute-engine.d.ts +1 -1
- package/dist/types/core.d.ts +1 -1
- package/dist/types/cortex/characters.d.ts +1 -1
- package/dist/types/cortex/diagnostics.d.ts +1 -1
- package/dist/types/cortex/execute-cortex.d.ts +1 -1
- package/dist/types/cortex/formatter.d.ts +1 -1
- package/dist/types/cortex/lexer.d.ts +1 -1
- package/dist/types/cortex/operators.d.ts +1 -1
- package/dist/types/cortex/parse-cortex.d.ts +1 -1
- package/dist/types/cortex/parser.d.ts +1 -1
- package/dist/types/cortex/reserved-words.d.ts +1 -1
- package/dist/types/cortex/serialize-cortex.d.ts +1 -1
- package/dist/types/cortex/tokens.d.ts +1 -1
- package/dist/types/cortex.d.ts +2 -2
- package/dist/types/identities.d.ts +1 -1
- package/dist/types/integration-rules.d.ts +1 -1
- package/dist/types/interval.d.ts +1 -1
- package/dist/types/latex-syntax.d.ts +2 -2
- package/dist/types/math-json/symbols.d.ts +1 -1
- package/dist/types/math-json/types.d.ts +1 -1
- package/dist/types/math-json/utils.d.ts +1 -1
- package/dist/types/math-json.d.ts +2 -2
- package/dist/types/numerics.d.ts +1 -1
- package/dist/umd-min/compile.cjs +14 -14
- package/dist/umd-min/compute-engine.cjs +14 -14
- package/dist/umd-min/core.cjs +14 -14
- package/dist/umd-min/cortex.cjs +15 -15
- package/dist/umd-min/identities.cjs +2 -2
- package/dist/umd-min/integration-rules.cjs +2 -2
- package/dist/umd-min/interval.cjs +2 -2
- package/dist/umd-min/latex-syntax.cjs +2 -2
- package/dist/umd-min/math-json.cjs +2 -2
- package/dist/umd-min/numerics.cjs +2 -2
- package/package.json +1 -1
package/dist/umd-min/cortex.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Cortex 0.86.
|
|
1
|
+
/** Cortex 0.86.2 */
|
|
2
2
|
(function(global,factory){typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'],factory):(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Cortex = {}));})(this, (function (exports) { 'use strict';
|
|
3
3
|
"use strict";var Cortex=(()=>{var D0=Object.defineProperty;var H7=Object.getOwnPropertyDescriptor;var Y7=Object.getOwnPropertyNames;var W7=Object.prototype.hasOwnProperty;var Q7=(e,n)=>{for(var t in n)D0(e,t,{get:n[t],enumerable:!0})},K7=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Y7(n))!W7.call(e,r)&&r!==t&&D0(e,r,{get:()=>n[r],enumerable:!(i=H7(n,r))||i.enumerable});return e};var X7=e=>K7(D0({},"__esModule",{value:!0}),e);var vK={};Q7(vK,{ComputeEngine:()=>yo,executeCortex:()=>J7,parseCortex:()=>w0,serializeCortex:()=>q7,version:()=>EK});var vt=Math.cosh||function(e){return Math.abs(e)<1e-9?1-e:(Math.exp(e)+Math.exp(-e))*.5},Ri=Math.sinh||function(e){return Math.abs(e)<1e-9?e:(Math.exp(e)-Math.exp(-e))*.5},e9=function(e){var n=Math.PI/4;if(-n>e||e>n)return Math.cos(e)-1;var t=e*e;return t*(t*(t*(t*(t*(t*(t*(t/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-1/2)},n9=function(e,n){var t=Math.abs(e),i=Math.abs(n);return t<3e3&&i<3e3?Math.sqrt(t*t+i*i):(t<i?(t=i,i=e/n):i=n/e,t*Math.sqrt(1+i*i))},xu=function(){throw SyntaxError("Invalid Param")};function O0(e,n){var t=Math.abs(e),i=Math.abs(n);return e===0?Math.log(i):n===0?Math.log(t):t<3e3&&i<3e3?Math.log(e*e+n*n)*.5:(e=e/2,n=n/2,.5*Math.log(e*e+n*n)+Math.LN2)}var t9=function(e,n){var t={re:0,im:0};if(e==null)t.re=t.im=0;else if(n!==void 0)t.re=e,t.im=n;else switch(typeof e){case"object":if("im"in e&&"re"in e)t.re=e.re,t.im=e.im;else if("abs"in e&&"arg"in e){if(!Number.isFinite(e.abs)&&Number.isFinite(e.arg))return L.INFINITY;t.re=e.abs*Math.cos(e.arg),t.im=e.abs*Math.sin(e.arg)}else if("r"in e&&"phi"in e){if(!Number.isFinite(e.r)&&Number.isFinite(e.phi))return L.INFINITY;t.re=e.r*Math.cos(e.phi),t.im=e.r*Math.sin(e.phi)}else e.length===2?(t.re=e[0],t.im=e[1]):xu();break;case"string":t.im=t.re=0;var i=e.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),r=1,o=0;i===null&&xu();for(var s=0;s<i.length;s++){var a=i[s];a===" "||a===" "||a===`
|
|
4
4
|
`||(a==="+"?r++:a==="-"?o++:a==="i"||a==="I"?(r+o===0&&xu(),i[s+1]!==" "&&!isNaN(Number(i[s+1]))?(t.im+=parseFloat((o%2?"-":"")+i[s+1]),s++):t.im+=parseFloat((o%2?"-":"")+"1"),r=o=0):((r+o===0||isNaN(Number(a)))&&xu(),i[s+1]==="i"||i[s+1]==="I"?(t.im+=parseFloat((o%2?"-":"")+a),s++):t.re+=parseFloat((o%2?"-":"")+a),r=o=0))}r+o>0&&xu();break;case"number":t.im=0,t.re=e;break;default:xu()}return isNaN(t.re)||isNaN(t.im),t},L=class e{constructor(n,t){this.re=0,this.im=0;var i=t9(n,t);this.re=i.re,this.im=i.im}sign(){var n=this.abs();return new e(this.re/n,this.im/n)}add(n,t){var i=new e(n,t);return this.isInfinite()&&i.isInfinite()?e.NAN:this.isInfinite()||i.isInfinite()?e.INFINITY:new e(this.re+i.re,this.im+i.im)}sub(n,t){var i=new e(n,t);return this.isInfinite()&&i.isInfinite()?e.NAN:this.isInfinite()||i.isInfinite()?e.INFINITY:new e(this.re-i.re,this.im-i.im)}mul(n,t){var i=new e(n,t);return this.isInfinite()&&i.isZero()||this.isZero()&&i.isInfinite()?e.NAN:this.isInfinite()||i.isInfinite()?e.INFINITY:i.im===0&&this.im===0?new e(this.re*i.re,0):new e(this.re*i.re-this.im*i.im,this.re*i.im+this.im*i.re)}div(n,t){var i=new e(n,t);if(this.isZero()&&i.isZero()||this.isInfinite()&&i.isInfinite())return e.NAN;if(this.isInfinite()||i.isZero())return e.INFINITY;if(this.isZero()||i.isInfinite())return e.ZERO;n=this.re,t=this.im;var r=i.re,o=i.im,s,a;return o===0?new e(n/r,t/r):Math.abs(r)<Math.abs(o)?(a=r/o,s=r*a+o,new e((n*a+t)/s,(t*a-n)/s)):(a=o/r,s=o*a+r,new e((n+t*a)/s,(t-n*a)/s))}pow(n,t){var i=new e(n,t);if(n=this.re,t=this.im,i.isZero())return e.ONE;if(i.im===0){if(t===0&&n>0)return new e(Math.pow(n,i.re),0);if(n===0)switch((i.re%4+4)%4){case 0:return new e(Math.pow(t,i.re),0);case 1:return new e(0,Math.pow(t,i.re));case 2:return new e(-Math.pow(t,i.re),0);case 3:return new e(0,-Math.pow(t,i.re))}}if(n===0&&t===0&&i.re>0&&i.im>=0)return e.ZERO;var r=Math.atan2(t,n),o=O0(n,t);return n=Math.exp(i.re*o-i.im*r),t=i.im*o+i.re*r,new e(n*Math.cos(t),n*Math.sin(t))}sqrt(){var n=this.re,t=this.im,i=this.abs(),r,o;if(n>=0){if(t===0)return new e(Math.sqrt(n),0);r=.5*Math.sqrt(2*(i+n))}else r=Math.abs(t)/Math.sqrt(2*(i-n));return n<=0?o=.5*Math.sqrt(2*(i-n)):o=Math.abs(t)/Math.sqrt(2*(i+n)),new e(r,t<0?-o:o)}exp(){var n=Math.exp(this.re);return this.im,new e(n*Math.cos(this.im),n*Math.sin(this.im))}expm1(){var n=this.re,t=this.im;return new e(Math.expm1(n)*Math.cos(t)+e9(t),Math.exp(n)*Math.sin(t))}log(){var n=this.re,t=this.im;return t===0&&n>0,new e(O0(n,t),Math.atan2(t,n))}abs(){return n9(this.re,this.im)}arg(){return Math.atan2(this.im,this.re)}sin(){var n=this.re,t=this.im;return new e(Math.sin(n)*vt(t),Math.cos(n)*Ri(t))}cos(){var n=this.re,t=this.im;return new e(Math.cos(n)*vt(t),-Math.sin(n)*Ri(t))}tan(){var n=2*this.re,t=2*this.im,i=Math.cos(n)+vt(t);return new e(Math.sin(n)/i,Ri(t)/i)}cot(){var n=2*this.re,t=2*this.im,i=Math.cos(n)-vt(t);return new e(-Math.sin(n)/i,Ri(t)/i)}sec(){var n=this.re,t=this.im,i=.5*vt(2*t)+.5*Math.cos(2*n);return new e(Math.cos(n)*vt(t)/i,Math.sin(n)*Ri(t)/i)}csc(){var n=this.re,t=this.im,i=.5*vt(2*t)-.5*Math.cos(2*n);return new e(Math.sin(n)*vt(t)/i,-Math.cos(n)*Ri(t)/i)}asin(){var n=this.re,t=this.im,i=new e(t*t-n*n+1,-2*n*t).sqrt(),r=new e(i.re-t,i.im+n).log();return new e(r.im,-r.re)}acos(){var n=this.re,t=this.im,i=new e(t*t-n*n+1,-2*n*t).sqrt(),r=new e(i.re-t,i.im+n).log();return new e(Math.PI/2-r.im,r.re)}atan(){var n=this.re,t=this.im;if(n===0){if(t===1)return new e(0,1/0);if(t===-1)return new e(0,-1/0)}var i=n*n+(1-t)*(1-t),r=new e((1-t*t-n*n)/i,-2*n/i).log();return new e(-.5*r.im,.5*r.re)}acot(){var n=this.re,t=this.im;if(t===0)return new e(Math.atan2(1,n),0);var i=n*n+t*t;return i!==0?new e(n/i,-t/i).atan():new e(n!==0?n/0:0,t!==0?-t/0:0).atan()}asec(){var n=this.re,t=this.im;if(n===0&&t===0)return new e(0,1/0);var i=n*n+t*t;return i!==0?new e(n/i,-t/i).acos():new e(n!==0?n/0:0,t!==0?-t/0:0).acos()}acsc(){var n=this.re,t=this.im;if(n===0&&t===0)return new e(Math.PI/2,1/0);var i=n*n+t*t;return i!==0?new e(n/i,-t/i).asin():new e(n!==0?n/0:0,t!==0?-t/0:0).asin()}sinh(){var n=this.re,t=this.im;return new e(Ri(n)*Math.cos(t),vt(n)*Math.sin(t))}cosh(){var n=this.re,t=this.im;return new e(vt(n)*Math.cos(t),Ri(n)*Math.sin(t))}tanh(){var n=2*this.re,t=2*this.im,i=vt(n)+Math.cos(t);return new e(Ri(n)/i,Math.sin(t)/i)}coth(){var n=2*this.re,t=2*this.im,i=vt(n)-Math.cos(t);return new e(Ri(n)/i,-Math.sin(t)/i)}csch(){var n=this.re,t=this.im,i=Math.cos(2*t)-vt(2*n);return new e(-2*Ri(n)*Math.cos(t)/i,2*vt(n)*Math.sin(t)/i)}sech(){var n=this.re,t=this.im,i=Math.cos(2*t)+vt(2*n);return new e(2*vt(n)*Math.cos(t)/i,-2*Ri(n)*Math.sin(t)/i)}asinh(){var n=this.im;this.im=-this.re,this.re=n;var t=this.asin();return this.re=-this.im,this.im=n,n=t.re,t.re=-t.im,t.im=n,t}acosh(){var n=this.acos();if(n.im<=0){var t=n.re;n.re=-n.im,n.im=t}else{var t=n.im;n.im=-n.re,n.re=t}return n}atanh(){var n=this.re,t=this.im,i=n>1&&t===0,r=1-n,o=1+n,s=r*r+t*t,a=s!==0?new e((o*r-t*t)/s,(t*r+o*t)/s):new e(n!==-1?n/0:0,t!==0?t/0:0),u=a.re;return a.re=O0(a.re,a.im)/2,a.im=Math.atan2(a.im,u)/2,i&&(a.im=-a.im),a}acoth(){var n=this.re,t=this.im;if(n===0&&t===0)return new e(0,Math.PI/2);var i=n*n+t*t;return i!==0?new e(n/i,-t/i).atanh():new e(n!==0?n/0:0,t!==0?-t/0:0).atanh()}acsch(){var n=this.re,t=this.im;if(t===0)return new e(n!==0?Math.log(n+Math.sqrt(n*n+1)):1/0,0);var i=n*n+t*t;return i!==0?new e(n/i,-t/i).asinh():new e(n!==0?n/0:0,t!==0?-t/0:0).asinh()}asech(){var n=this.re,t=this.im;if(this.isZero())return e.INFINITY;var i=n*n+t*t;return i!==0?new e(n/i,-t/i).acosh():new e(n!==0?n/0:0,t!==0?-t/0:0).acosh()}inverse(){if(this.isZero())return e.INFINITY;if(this.isInfinite())return e.ZERO;var n=this.re,t=this.im,i=n*n+t*t;return new e(n/i,-t/i)}conjugate(){return new e(this.re,-this.im)}neg(){return new e(-this.re,-this.im)}ceil(n){return n=Math.pow(10,n||0),new e(Math.ceil(this.re*n)/n,Math.ceil(this.im*n)/n)}floor(n){return n=Math.pow(10,n||0),new e(Math.floor(this.re*n)/n,Math.floor(this.im*n)/n)}round(n){return n=Math.pow(10,n||0),new e(Math.round(this.re*n)/n,Math.round(this.im*n)/n)}equals(n,t){var i=new e(n,t);return Math.abs(i.re-this.re)<=e.EPSILON&&Math.abs(i.im-this.im)<=e.EPSILON}clone(){return new e(this.re,this.im)}toString(){var n=this.re,t=this.im,i="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(n)<e.EPSILON&&(n=0),Math.abs(t)<e.EPSILON&&(t=0),t===0?i+n:(n!==0?(i+=n,i+=" ",t<0?(t=-t,i+="-"):i+="+",i+=" "):t<0&&(t=-t,i+="-"),t!==1&&(i+=t),i+"i"))}toVector(){return[this.re,this.im]}valueOf(){return this.im===0?this.re:null}isNaN(){return isNaN(this.re)||isNaN(this.im)}isZero(){return this.im===0&&this.re===0}isFinite(){return isFinite(this.re)&&isFinite(this.im)}isInfinite(){return!(this.isNaN()||this.isFinite())}};L.ZERO=new L(0,0);L.ONE=new L(1,0);L.I=new L(0,1);L.PI=new L(Math.PI,0);L.E=new L(Math.E,0);L.INFINITY=new L(1/0,1/0);L.NAN=new L(NaN,NaN);L.EPSILON=1e-15;var BN=new Map,i9=1e5;function Be(e){if(e<=i9){let n=BN.get(e);return n===void 0&&(n=10n**BigInt(e),BN.set(e,n)),n}return 10n**BigInt(e)}function vo(e){if(e<0n&&(e=-e),e===0n)return 0;let n=0,t=1;for(;e>>BigInt(t)>0n;)t*=2;for(let i=t>>1;i>=1;i>>=1)e>>BigInt(i)>0n&&(n+=i,e>>=BigInt(i));return n+1}function qN(e,n,t){return e*n>>BigInt(t)}function VN(e,n,t){return(e<<BigInt(t))/n}function Od(e,n){if(e===0n)return 0n;if(e<0n)throw new RangeError("fpsqrt: negative input");let t=e<<BigInt(n),i;if(n<r9){i=F0(t);let a;do a=i,i=(i+t/i)/2n;while(Pi(i-a)>1n)}else i=B0(t,vo(t));let r=(i+t/i)/2n,o=Pi(i*i-t);return Pi(r*r-t)<o?r:i}function F0(e){let n=vo(e);if(n<=1023){let s=Math.sqrt(Number(e));if(Number.isFinite(s)&&s>=1)return BigInt(Math.floor(s))}let t=n-52,i=Number(e>>BigInt(t)),r=Math.sqrt(i);t&1&&(r*=Math.SQRT2);let o=BigInt(Math.round(r))<<BigInt(t>>1);return o>0n?o:1n}var JN=1024,r9=640;function B0(e,n){if(n<JN){let o=F0(e),s;do s=o,o=(o+e/o)/2n;while(Pi(o-s)>1n);for(;o*o>e;)o-=1n;for(;(o+1n)*(o+1n)<=e;)o+=1n;return o}let t=n>>2<<1,i=B0(e>>BigInt(t),n-t)<<BigInt(t>>1),r;do r=i,i=(i+e/i)/2n;while(Pi(i-r)>1n);for(;i*i>e;)i-=1n;for(;(i+1n)*(i+1n)<=e;)i+=1n;return i}function Pi(e){return e<0n?-e:e}function vu(e){if(e===0n)return 1;if(e<0n&&(e=-e),e<0x20000000000000n){let i=Number(e);return i<1e8?i<1e4?i<100?i<10?1:2:i<1e3?3:4:i<1e6?i<1e5?5:6:i<1e7?7:8:i<1e12?i<1e10?i<1e9?9:10:i<1e11?11:12:i<1e14?i<1e13?13:14:i<1e15?15:16}let n=e.toString(16).length*4,t=Math.ceil(n*.30102999566398);for(;e<Be(t-1);)t--;for(;e>=Be(t);)t++;return t}var o9=.7;function $0(e,n){if(e===0n)return 1n<<BigInt(n);let t=Math.round(o9*Math.sqrt(n)),i=t+8,r=n+i,o=BigInt(r),s=1n<<o,a=BigInt(i),u=e<<a,l=u<0n,c=l?-u:u,f=Math.max(0,vo(c)-r+t);c>>=BigInt(f),u=l?-c:c;let p=s,d=u;p+=d;for(let g=2;d=(d*u>>o)/BigInt(g),d!==0n;g++)p+=d;for(let g=0;g<f;g++)p=p*p>>o;return p+(1n<<a-1n)>>a}var s9=4e4;function q0(e,n){let t=1n<<BigInt(n);if(e<=0n)throw new RangeError("fpln: input must be positive");return e===t?0n:n>=s9?l9(e,n):a9(e,n)}function a9(e,n){let t=BigInt(n),i=1n<<t,r=52,o=n-r,s;if(o>0){let g=Number(e>>BigInt(o))/2**r;s=BigInt(Math.round(Math.log(g)*2**r))<<BigInt(o)}else{let g=Number(e)/Number(i);s=BigInt(Math.round(Math.log(g)*Number(i)))}let a=e*$0(-s,n)>>t,l=(a-i<<t)/(a+i),c=l<0n?-l:l,f=c*c>>t,p=c,d=c;for(let g=3n;p=p*f>>t,p!==0n;g+=2n)d+=p/g;return s+(l<0n?-2n:2n)*d}var la=null;function u9(e){if(la!==null){if(la.bits===e)return la.value;if(la.bits>e)return la.value>>BigInt(la.bits-e)}let n=Math.ceil(e*Ld)+12,t;if(n<=$N.length){let i=$N.slice(0,n);t=(BigInt(i)<<BigInt(e))/Be(i.length)}else t=g9(e);return la={bits:e,value:t},t}function l9(e,n){let t=BigInt(n),i=vo(e)-n,r=Math.max(2,Math.ceil(n/2+4-i)),o=e<<BigInt(r-2),s=1n<<t,a=o;for(;Pi(s-a)>1n;){let l=s+a>>1n;a=Pc(s*a),s=l}return Dd(n)*o/(2n*s)-BigInt(r)*u9(n)}var Eu="314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837297804995105973173281609631859502445945534690830264252230825334468503526193118817101000313783875288658753320838142061717766914730359825349042875546873115956286388235378759375195778185778053217122680661300192787661119590921642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151557485724245415069595082953311686172785588907509838175463746493931925506040092770167113900984882401285836160356370766010471018194295559619894676783744944825537977472684710404753464620804668425906949129331367702898915210475216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992458631503028618297455570674983850549458858692699569092721079750930295532116534498720275596023648066549911988183479775356636980742654252786255181841757467289097777279380008164706001614524919217321721477235014144197356854816136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179049460165346680498862723279178608578438382796797668145410095388378636095068006422512520511739298489608412848862694560424196528502221066118630674427862203919494504712371378696095636437191728746776465757396241389086583264599581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745530506820349625245174939965143142980919065925093722169646151570985838741059788595977297549893016175392846813826868386894277415599185592524595395943104997252468084598727364469584865383673622262609912460805124388439045124413654976278079771569143599770012961608944169486855584840635",Ld=Math.log10(2),$N="693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687542001481020570685733685520235758130557032670751635075961930727570828371435190307038623891673471123350115364497955239120475172681574932065155524734139525882950453007095326366642654104239157814952043740430385500801944170641671518644712839968171784546957026271631064546150257207402481637773389638550695260668341137273873722928956493547025762652098859693201965058554764703306793654432547632744951250406069438147104689946506220167720424524529612687946546193165174681392672504103802546259656869144192871608293803172714367782654877566485085674077648451464439940461422603193096735402574446070308096085047486638523138181676751438667476647890881437141985494231519973548803751658612753529166100071053558249879414729509293113897155998205654392871700072180857610252368892132449713893203784393530887748259701715591070882368362758984258918535302436342143670611892367891923723146723217205340164925687274778234453534764811494186423867767744060695626573796008670762571991847340226514628379048830620330611446300737194890027436439650025809365194430411911506080948793067865158870900605203468429736193841289652556539686022194122924207574321757489097706752687115817051137009158942665478595964890653058460258668382940022833005382074005677053046787001841624044188332327983863490015631218895606505531512721993983320307514084260914790012651682434438935724727882054862715527418772430024897945401961872339808608316648114909306675193393128904316413706813977764981769748689038877899912965036192707108892641052309247839173735012298424204995689359922066022046549415106139187885744245577510206837030866619480896412186807790208181588580001688115973056186676199187395200766719214592236720602539595436541655311295175989940056000366513567569051245926825743946483168332624901803824240824231452306140963805700702551387702681785163069025513703234053802145019015374029509942262995779647427138157363801729873940704242179972266962979939312706935747240493386530879758721699645129446491883771156701678598804981838896784134938314014073166472765327635919233511233389338709513209059272185471328975470797891384445466676192702885533423429899321803769154973340267546758873236778342916191810430116091695265547859732891763545556742863877463987101912431754255888301206779210280341206879759143081283307230300883494705792496591005860012341561757413272465943",c9=13591409n,f9=545140134n,p9=10939058860032000n,d9=47.11;function Pd(e,n){if(n-e===1){let l,c;if(e===0)l=1n,c=1n;else{l=BigInt(6*e-5)*BigInt(2*e-1)*BigInt(6*e-1);let p=BigInt(e);c=p*p*p*p9}let f=l*(c9+f9*BigInt(e));return e&1&&(f=-f),[l,c,f]}let t=e+n>>1,[i,r,o]=Pd(e,t),[s,a,u]=Pd(t,n);return[i*s,r*a,a*o+i*u]}function jN(e){return Math.max(2,Math.floor(e/d9)+3)}function m9(e){let[,n,t]=Pd(0,jN(e)),i=1n<<BigInt(e),r=Pc(10005n*i*i);return n*426880n*r/t}function zN(e){let[,n,t]=Pd(0,jN(Math.ceil(e/Ld))),i=Be(e),r=Pc(10005n*i*i);return n*426880n*r/t}function L0(e,n){if(n-e===1){let l=e===0?1n:BigInt(2*e-1),c=e===0?1n:9n*BigInt(2*e+1);return[l,c,l]}let t=e+n>>1,[i,r,o]=L0(e,t),[s,a,u]=L0(t,n);return[i*s,r*a,a*o+i*u]}function g9(e){let n=Math.max(2,Math.ceil(e/3.169925)+5),[,t,i]=L0(0,n);return(i<<BigInt(e+1))/(3n*t)}function Pc(e){if(e<0n)throw new RangeError("bigintSqrt: negative input");if(e===0n)return 0n;let n=vo(e);if(n>=JN)return B0(e,n);let t=F0(e),i;do i=t,t=(t+e/t)/2n;while(Pi(t-i)>1n);for(;t*t>e;)t-=1n;for(;(t+1n)*(t+1n)<=e;)t+=1n;return t}var ca=null;function Dd(e){if(ca!==null){if(ca.bits===e)return ca.value;if(ca.bits>e)return ca.value>>BigInt(ca.bits-e)}let n=h9(e);return ca={bits:e,value:n},n}function h9(e){let n=Math.ceil(e*Ld)+12;if(n+1<=Eu.length){let t=Eu.slice(0,n+1);return(BigInt(t)<<BigInt(e))/Be(t.length-1)}return m9(e)}function Fd(e,n){let t=BigInt(n),i=1n<<t;if(e===0n)return[0n,i];let r=Dd(n),o=2n*r,s=r/2n,a,u=Pi(e);if(u>i<<30n){let _=vo(u)-n+64,I=n+_,T=e<<BigInt(_),A=2n*Dd(I),P=T%A;P<0n&&(P+=A),a=P>>BigInt(_)}else a=e%o;a<0n&&(a+=o);let l=1n,c=1n;a>3n*s?(a=o-a,l=-1n):a>r?(a=a-r,l=-1n,c=-1n):a>s&&(a=r-a,c=-1n);let f=Math.round(n*Ld),p=Math.min(18,Math.max(2,Math.ceil(.87*Math.sqrt(f)))),d=0,g=i>>BigInt(p);for(;a>g;)a=a/2n,d++;let h=a,b=i,y=a,x=i,E=a*a,v=2n*t;for(let _=2;;_+=2){if(x=(x*E>>v)/(BigInt(_)*BigInt(_-1)),x===0n){y=(y*E>>v)/(BigInt(_+1)*BigInt(_)),y!==0n&&(_%4===2?(b-=x,h-=y):(b+=x,h+=y));break}if(y=(y*E>>v)/(BigInt(_+1)*BigInt(_)),_%4===2?(b-=x,h-=y):(b+=x,h+=y),y===0n)break}for(let _=0;_<d;_++){let I=2n*h*b>>t,T=(2n*b*b>>t)-i;h=I,b=T}return[l*h,c*b]}function Rc(e,n){if(e===0n)return 0n;if(e<0n)return-Rc(-e,n);let t=BigInt(n),i=1n<<t,o=Dd(n)/2n;if(e>i){let d=(i<<t)/e;return o-Rc(d,n)}let s=4n*i/10n,a=0,u=e;for(;u>s;){let d=u*u,g=(i<<t)+d>>t,h=Od(g,n);u=(u<<t)/(i+h),a++}let l=u,c=u,f=u*u,p=2n*t;for(let d=3;c=c*f>>p,c!==0n;d+=2)d%4===3?l-=c/BigInt(d):l+=c/BigInt(d);for(let d=0;d<a;d++)l=2n*l;return l}var V0=NaN,S=class e{static precision=50;static ZERO=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:0n,exponent:0}));static ONE=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:1n,exponent:0}));static TWO=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:2n,exponent:0}));static NEGATIVE_ONE=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:-1n,exponent:0}));static HALF=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:5n,exponent:-1}));static NAN=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:0n,exponent:NaN}));static POSITIVE_INFINITY=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:1n,exponent:1/0}));static NEGATIVE_INFINITY=Object.freeze(Object.assign(Object.create(e.prototype),{_digits:1,significand:-1n,exponent:1/0}));static _piFullPrecision=null;static _piCache=null;static _piCachePrecision=0;static _eulerGammaCache=null;static _eulerGammaCachePrecision=0;static get PI(){let n=e.precision;if(e._piCache!==null&&e._piCachePrecision===n)return e._piCache;let t=n+4,i;if(t+1<=Eu.length)e._piFullPrecision===null&&(e._piFullPrecision=new e(Eu[0]+"."+Eu.slice(1))),i=e._piFullPrecision.toPrecision(t);else{let r=t+4;i=$e(zN(r),-r).toPrecision(t)}return e._piCache=i,e._piCachePrecision=n,i}static get EULER_GAMMA(){let n=e.precision;if(e._eulerGammaCache!==null&&e._eulerGammaCachePrecision>=n)return e._eulerGammaCache.toPrecision(n);let t=x9(n);return e._eulerGammaCache=t,e._eulerGammaCachePrecision=n,t}significand;exponent;_digits;digitCount(){return this._digits??(this._digits=vu(this.significand))}constructor(n){if(n instanceof e){this.significand=n.significand,this.exponent=n.exponent;return}if(typeof n=="bigint"){[this.significand,this.exponent]=Bd(n,0);return}if(typeof n=="number"){[this.significand,this.exponent]=E9(n);return}[this.significand,this.exponent]=YN(n)}isNaN(){return Number.isNaN(this.exponent)}isZero(){return this.exponent===0&&this.significand===0n}isFinite(){return Number.isFinite(this.exponent)}isInteger(){return this.isFinite()&&this.exponent>=0}isPositive(){return this.significand>0n}isNegative(){return this.significand<0n}cmp(n){if(typeof n=="number"){if(Number.isNaN(n))return V0;let d=this.exponent;if(Number.isNaN(d))return V0;if(n===0)return this.significand===0n?0:this.significand>0n?1:-1;if(!Number.isFinite(d))return n===1/0?this.significand>0n?0:-1:n===-1/0?this.significand<0n?0:1:this.significand>0n?1:-1;if(this.significand===0n)return n>0?-1:1;if(n===1/0)return-1;if(n===-1/0)return 1;if(this.significand>0n!=n>0)return this.significand>0n?1:-1;if(Number.isInteger(n)&&d>=0&&d<=15){let g=this.significand*Be(d),h=BigInt(n);return g<h?-1:g>h?1:0}n=new e(n)}let t=this.exponent,i=n.exponent,r=this.significand,o=n.significand;if(t!==t||i!==i)return V0;if(!Number.isFinite(t)||!Number.isFinite(i))return!Number.isFinite(t)&&!Number.isFinite(i)?r===o?0:r>o?1:-1:Number.isFinite(t)?o>0n?-1:1:r>0n?1:-1;if(r===0n)return o===0n?0:o>0n?-1:1;if(o===0n)return r>0n?1:-1;if(r>0n&&o<0n)return 1;if(r<0n&&o>0n)return-1;if(t===i)return r<o?-1:r>o?1:0;let s=this.digitCount(),a=n.digitCount(),u=s+t,l=a+i;if(u!==l){let d=r>0n?1:-1;return u>l?d:-d}let c=r,f=o,p=Math.abs(t-i);if(p>1e3){let d=s,g=a,h=Math.max(d,g)+1;d<h&&(c=c*Be(h-d)),g<h&&(f=f*Be(h-g))}else t<i?f=f*Be(p):c=c*Be(p);return c<f?-1:c>f?1:0}eq(n){return typeof n=="number"?n===0?this.significand===0n&&this.exponent===0:n===1?this.significand===1n&&this.exponent===0:n===-1?this.significand===-1n&&this.exponent===0:Number.isInteger(n)&&Number.isFinite(this.exponent)&&this.exponent>=0&&this.exponent<=15?this.significand*Be(this.exponent)===BigInt(n):this.cmp(n)===0:this.significand===n.significand&&this.exponent===n.exponent}lt(n){return this.cmp(n)===-1}lte(n){let t=this.cmp(n);return t===-1||t===0}gt(n){return this.cmp(n)===1}gte(n){let t=this.cmp(n);return t===1||t===0}add(n){typeof n=="number"&&(n=new e(n));let t=this.exponent,i=n.exponent;if(Number.isFinite(t)&&Number.isFinite(i)){if(t===i)return $e(this.significand+n.significand,t);let s=t-i;return s>0?$e(this.significand*Be(s)+n.significand,i):$e(this.significand+n.significand*Be(-s),t)}if(t!==t||i!==i)return e.NAN;let r=!Number.isFinite(t),o=!Number.isFinite(i);return r&&o?this.significand!==n.significand?e.NAN:this.significand>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY:r?this.significand>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY:n.significand>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY}sub(n){typeof n=="number"&&(n=new e(n));let t=this.exponent,i=n.exponent;if(Number.isFinite(t)&&Number.isFinite(i)){if(t===i)return $e(this.significand-n.significand,t);let s=t-i;return s>0?$e(this.significand*Be(s)-n.significand,i):$e(this.significand-n.significand*Be(-s),t)}if(t!==t||i!==i)return e.NAN;let r=!Number.isFinite(t),o=!Number.isFinite(i);return r&&o?this.significand===n.significand?e.NAN:this.significand>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY:r?this.significand>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY:n.significand>0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY}mul(n){typeof n=="number"&&(n=new e(n));let t=this.exponent,i=n.exponent;if(Number.isFinite(t)&&Number.isFinite(i))return $e(this.significand*n.significand,t+i);if(t!==t||i!==i||this.significand===0n||n.significand===0n)return e.NAN;let r=this.significand>0n?1n:-1n,o=n.significand>0n?1n:-1n;return r*o>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY}mulToPrecision(n,t){typeof n=="number"&&(n=new e(n));let i=this.exponent,r=n.exponent,o=this.significand,s=n.significand;if(o!==0n&&s!==0n&&Number.isFinite(i)&&Number.isFinite(r)){let a=o*s,u=i+r,l=this.digitCount()+n.digitCount()-1,f=(a<0n?-a:a)>=Be(l)?l+1:l;return f<=t?$e(a,u):GN(a,u).roundToPrecKnownDigits(t,f)}return this.mul(n).toPrecision(t)}neg(){let n=this.significand;return n===0n?this:Number.isFinite(this.exponent)?$e(-n,this.exponent):n>0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY}abs(){return this.significand>=0n?this:Number.isFinite(this.exponent)?$e(-this.significand,this.exponent):e.POSITIVE_INFINITY}floor(){let n=this.exponent;if(n>=0)return this;if(Number.isFinite(n)){let t=this.trunc();return this.significand<0n?t.sub($e(1n,0)):t}return this}ceil(){let n=this.exponent;if(n>=0)return this;if(Number.isFinite(n)){let t=this.trunc();return this.significand>0n?t.add($e(1n,0)):t}return this}round(){let n=this.exponent;if(n>=0)return this;if(Number.isFinite(n)){let t=$e(5n,-1);return this.significand>0n?this.add(t).trunc():this.sub(t).trunc()}return this}trunc(){let n=this.exponent;if(n>=0)return this;if(Number.isFinite(n)){let t=this.significand/Be(-n);return $e(t===0n?0n:t,0)}return this}div(n){typeof n=="number"&&(n=new e(n));let t=this.exponent,i=n.exponent,r=this.significand,o=n.significand;if(Number.isFinite(t)&&Number.isFinite(i)){if(o===0n)return r===0n?e.NAN:r>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY;if(r===0n)return $e(0n,0);let u=e.precision,l=10,c=this.digitCount(),f=n.digitCount(),p=u+l+Math.max(0,f-c),d=Be(p),g=r*d/o,h=t-i-p,b=g<0n?-g:g,y=c+p-f,x=b>=Be(y)?y+1:y;return GN(g,h).roundToPrecKnownDigits(u,x)}if(t!==t||i!==i)return e.NAN;let s=!Number.isFinite(t),a=!Number.isFinite(i);if(s&&a)return e.NAN;if(s){let u=r>0n?1n:-1n,l=o>0n?1n:o<0n?-1n:1n;return u*l>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY}return $e(0n,0)}inv(){return $e(1n,0).div(this)}divToward(n,t){typeof n=="number"&&(n=new e(n));let i=this.exponent,r=n.exponent,o=this.significand,s=n.significand;if(!Number.isFinite(i)||!Number.isFinite(r)||s===0n||o===0n)return this.div(n);let a=o<0n!=s<0n,u=o<0n?-o:o,l=s<0n?-s:s,c=e.precision,p=c+10+Math.max(0,n.digitCount()-this.digitCount()),d=u*Be(p),g=d/l,h=d%l!==0n,b=i-r-p,y=this.digitCount()+p-n.digitCount(),x=g>=Be(y)?y+1:y,E=a?t==="floor":t==="ceiling",[v,_]=UN(g,h,b,c,E,x);return $e(a?-v:v,_)}sqrtToward(n){if(this.significand===0n)return this.exponent!==this.exponent?this:e.ZERO;if(!Number.isFinite(this.exponent))return this.significand>0n?e.POSITIVE_INFINITY:e.NAN;if(this.significand<0n)return e.NAN;let t=e.precision,i=4,r=this.significand,o=this.exponent,s=o+this.digitCount()-1,a=Math.floor(s/2),u=t+i-a;o+2*u<0&&(u=Math.ceil(-o/2)+1);let l=o+2*u,c=l>=0?r*Be(l):r/Be(-l),f=Pc(c),p=f*f!==c,[d,g]=UN(f,p,-u,t,n==="ceiling");return $e(d,g)}mod(n){typeof n=="number"&&(n=new e(n));let t=this.exponent,i=n.exponent;if(Number.isFinite(t)&&Number.isFinite(i)){if(n.significand===0n)return e.NAN;if(this.significand===0n)return $e(0n,0);let r=t-i,o=r>=0?this.significand*Be(r):this.significand,s=r>=0?n.significand:n.significand*Be(-r),a=o/s;return this.sub($e(a,0).mul(n))}return t!==t||i!==i||!Number.isFinite(t)?e.NAN:new e(this)}pow(n){if(typeof n=="number"&&(n=new e(n)),this.isNaN()||n.isNaN()||!n.isFinite())return e.NAN;if(n.isInteger()){let a=n.toBigInt();if(a===0n)return $e(1n,0);if(!this.isFinite())return a>0n?this.significand<0n&&a%2n!==0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY:$e(0n,0);if(this.isZero())return a>0n?$e(0n,0):e.POSITIVE_INFINITY;if(a<0n)return this.pow(n.neg()).inv();let u=this.significand<0n?-this.significand:this.significand,l=this.digitCount(),c=l>15?l-15:0,f=c>0?Number(u/10n**BigInt(c)):Number(u),p=Math.log10(f)+c+this.exponent,d=Number(a)*p;if(d>9e15)return this.significand<0n&&a%2n!==0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY;if(d<-9e15)return $e(0n,0);let g=e.precision,h=a.toString(2).length,b=Math.min(2*h+5,100),y=g+b,x=$e(1n,0),E=this,v=a;for(;v>0n;)v&1n&&(x=x.mulToPrecision(E,y)),v>>=1n,v>0n&&(E=E.mulToPrecision(E,y));return x.toPrecision(g)}if(!this.isFinite())return this.significand<0n?e.NAN:n.significand>0n?e.POSITIVE_INFINITY:e.ZERO;if(this.isZero())return n.significand>0n?e.ZERO:e.POSITIVE_INFINITY;if(this.significand<0n)return e.NAN;let t=this.exponent+this.digitCount()-1,r=n.exponent+n.digitCount()-1+Math.log10(Math.abs(t)*2.303+3)+1,o=Math.min(20,Math.max(2,Math.ceil(r)+2)),s=e.precision;e.precision=s+o;try{let a=y9(this,s+o);return n.mul(a).exp().toPrecision(s)}finally{e.precision=s}}toNumber(){return Number.isFinite(this.exponent)?this.significand===0n?0:this.exponent===0?Number(this.significand):Number(this.toString()):this.exponent!==this.exponent?NaN:this.significand>0n?1/0:-1/0}toString(){if(!Number.isFinite(this.exponent))return this.exponent!==this.exponent?"NaN":this.significand>0n?"Infinity":"-Infinity";if(this.significand===0n)return"0";let n=this.significand<0n,t=(n?-this.significand:this.significand).toString(),i=t.length,r=i+this.exponent-1,o=n?"-":"";if(r>20||r<-6){let u=i===1?t:t[0]+"."+t.slice(1),l=r>=0?"+":"";return`${o}${u}e${l}${r}`}if(this.exponent>=0)return o+t+"0".repeat(this.exponent);let s=-this.exponent;if(s<i){let u=t.slice(0,i-s),l=t.slice(i-s);return`${o}${u}.${l}`}let a=s-i;return`${o}0.${"0".repeat(a)}${t}`}toFixed(n){let t=n??0;if(!Number.isFinite(this.exponent))return this.exponent!==this.exponent?"NaN":this.significand>0n?"Infinity":"-Infinity";let i=this.significand<0n,r=i?-this.significand:this.significand,o=this.exponent+t,s,a;if(o>=0)a=r===0n,s=a?"0":r.toString()+"0".repeat(o);else{let f=Be(-o),p=r/f,d=r%f,g=f/2n,h;d>g?h=p+1n:d<g||f%2n!==0n||p%2n===0n?h=p:h=p+1n,a=h===0n,s=h.toString()}let u=i&&!a?"-":"";if(t===0)return`${u}${s}`;if(s.length<=t){let f=s.padStart(t,"0");return`${u}0.${f}`}let l=s.slice(0,s.length-t),c=s.slice(s.length-t);return`${u}${l}.${c}`}toPrecision(n){if(this.significand===0n||!Number.isFinite(this.exponent))return this;let t=this.digitCount();return t<=n?this:this.roundToPrecKnownDigits(n,t)}roundToPrecKnownDigits(n,t){let i=this.significand<0n?-this.significand:this.significand,r=t-n,o=Be(r),s=i/o,a=i-s*o,u=o/2n;(a>u||a===u&&s%2n!==0n)&&(s+=1n);let l=this.significand<0n?-s:s;return $e(l,this.exponent+r)}toBigInt(){if(!Number.isFinite(this.exponent))throw this.exponent!==this.exponent?new RangeError("Cannot convert NaN to BigInt"):new RangeError("Cannot convert Infinity to BigInt");if(this.exponent>=0)return this.significand*Be(this.exponent);let n=Be(-this.exponent);return this.significand/n}},b9=8,Dc=[];function y9(e,n){let t=e.significand,i=e.exponent;for(let o=Dc.length-1;o>=0;o--){let s=Dc[o];if(s.prec===n&&s.exp===i&&s.sig===t)return s.ln}let r=e.ln();return Dc.push({sig:t,exp:i,prec:n,ln:r}),Dc.length>b9&&Dc.shift(),r}function x9(e){let n=e+20+Math.ceil(Math.log10(e+10)),t=S.precision;S.precision=n;try{let i=Math.ceil(n*Math.LN10/4)+5,r=new S(i),o=r.mul(r),s=S.ONE,a=S.ONE,u=S.ZERO,l=S.ZERO,c=S.ONE.div(new S(10).pow(n)),f=6*i+100;for(let p=1;p<=f;p++){let d=new S(p).mul(p);if(s=s.mul(o).div(d).toPrecision(n),l=l.add(S.ONE.div(p)).toPrecision(n),a=a.add(s).toPrecision(n),u=u.add(s.mul(l)).toPrecision(n),p>i&&s.lt(a.mul(c)))break}return u.div(a).sub(r.ln()).toPrecision(e)}finally{S.precision=t}}function $e(e,n){let[t,i]=Bd(e,n),r=Object.create(S.prototype);return r.significand=t,r.exponent=i,r}function GN(e,n){let t=Object.create(S.prototype);return t.significand=e,t.exponent=n,t}function UN(e,n,t,i,r,o){if(e===0n)return[r&&n?1n:0n,t];let s=o??vu(e);if(s<=i)return[r&&n?e+1n:e,t];let a=s-i,u=Be(a),l=e/u,c=n||e%u!==0n;return r&&c&&(l+=1n),[l,t+a]}var ZN=1000000000n,HN=1000n;function Bd(e,n){if(e===0n)return[0n,0];if((e&1n)!==0n)return[e,n];if(e%10n!==0n)return[e,n];for(;e%ZN===0n;)e/=ZN,n+=9;for(;e%HN===0n;)e/=HN,n+=3;for(;e%10n===0n;)e/=10n,n+=1;return[e,n]}function E9(e){return Number.isNaN(e)?[0n,NaN]:e===1/0?[1n,1/0]:e===-1/0?[-1n,1/0]:Number.isInteger(e)?Bd(BigInt(e),0):YN(e.toString())}function YN(e){if(e=e.trim(),e===""||e==="NaN")return[0n,NaN];if(e==="Infinity"||e==="+Infinity")return[1n,1/0];if(e==="-Infinity")return[-1n,1/0];let n,t=0,i=e.search(/[eE]/);if(i!==-1){if(n=e.slice(0,i),t=Number(e.slice(i+1)),!Number.isFinite(t))return[0n,NaN]}else n=e;let r=!1;n.startsWith("-")?(r=!0,n=n.slice(1)):n.startsWith("+")&&(n=n.slice(1));let o=n.indexOf("."),s,a;o===-1?(s=n,a=""):(s=n.slice(0,o),a=n.slice(o+1)),s=s.replace(/^0+/,"")||"0";let u=s+a;if(u.length===0||!/^\d+$/.test(u))return[0n,NaN];let l=BigInt(u);r&&(l=-l);let c=-a.length;return Bd(l,c+t)}var v9=Math.log2(10),KN=Math.log10(2),S9=16,j0=1e6;function So(e,n){let t=Math.ceil(n*v9)+S9,i=BigInt(t);return e.exponent>=0?[e.significand*Be(e.exponent)<<i,t]:[(e.significand<<i)/Be(-e.exponent),t]}function _o(e,n,t){if(e===0n)return S.ZERO;let i=e<0n,r=i?-e:e,o=BigInt(n),s=vo(r)-n,a=Math.floor(s*KN),u=t+4-a,l,c;if(u>=0)l=r*Be(u)+(1n<<o-1n)>>o,c=-u;else{let p=Be(-u)<<o;l=(r+p/2n)/p,c=-u}if(l===0n)return S.ZERO;let f=vu(l);if(f>t){let p=f-t,d=Be(p),g=d/2n,h=l%d;l=l/d,h>=g&&(l+=1n),c+=p}return $e(i?-l:l,c)}function Ot(e){return e.exponent+e.digitCount()-1}function J0(e,n){if(e===0n)return 0;let t=e<0n?-e:e,i=n*KN-(vu(t)-1);return i>0?Math.ceil(i):0}var XN=5,WN=BigInt(Number.MAX_SAFE_INTEGER),fa=null;function ew(e){if(fa!==null){if(fa.bits===e)return fa.value;if(fa.bits>e)return fa.value>>BigInt(fa.bits-e)}let n=q0(10n<<BigInt(e),e);return fa={bits:e,value:n},n}S.prototype.sqrt=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NAN;if(this.significand<0n)return S.NAN;let e=S.precision,n=e+10,t=Ot(this),i=Math.floor(t/2),r=$e(this.significand,this.exponent-2*i),[o,s]=So(r,n),a=Od(o,s),u=_o(a,s,e);return $e(u.significand,u.exponent+i)};S.prototype.cbrt=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NEGATIVE_INFINITY;if(this.significand<0n)return this.neg().cbrt().neg();let e=S.precision,n=e+10,t=Ot(this),i=Math.floor(t/3),r=$e(this.significand,this.exponent-3*i),[o,s]=So(r,n),a=o<<BigInt(2*s),u,l=r.toNumber();if(s<=1e3&&Number.isFinite(l)&&l>0){let p=Number(1n<<BigInt(s)),d=Math.cbrt(l);Number.isFinite(d)&&d>0?(u=BigInt(Math.floor(d*p)),u===0n&&(u=1n)):u=QN(a)}else u=QN(a);let c;do{c=u;let p=u*u;if(p===0n){u=1n;break}u=(2n*u+a/p)/3n}while(Pi(u-c)>1n);{let p=(2n*u+a/(u*u))/3n,d=Pi(u*u*u-a);Pi(p*p*p-a)<d&&(u=p)}let f=_o(u,s,e);return $e(f.significand,f.exponent+i)};S.sqrt=function(e){return e.sqrt()};S.cbrt=function(e){return e.cbrt()};S.prototype.exp=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.ZERO;if(this.isZero())return S.ONE;if(Ot(this)>=17)return this.significand>0n?S.POSITIVE_INFINITY:S.ZERO;let e=S.precision,n=Math.max(0,this.exponent+this.digitCount()),t=e+20+n,[i,r]=So(this,t),o=ew(r),s=i/o,a=i-s*o;if(a<0n&&(s-=1n,a+=o),s>WN||s<-WN)return s>0n?S.POSITIVE_INFINITY:S.ZERO;let u=_o($0(a,r),r,e),l=u.exponent+Number(s);return Number.isSafeInteger(l)?$e(u.significand,l):s>0n?S.POSITIVE_INFINITY:S.ZERO};S.prototype.ln=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NAN;if(this.isZero())return S.NEGATIVE_INFINITY;if(this.significand<0n)return S.NAN;if(this.eq(1))return S.ZERO;let e=S.precision,n=this.significand,t=this.digitCount(),i=this.exponent+t-1,r=$e(n,-(t-1)),o=Math.abs(i).toString().length,s=0;if(i===0||i===-1){let p=this.sub(S.ONE);if(!p.isZero()){let d=Ot(p);d<0&&(s=-d)}}let a=e+20+o+s,[u,l]=So(r,a),c=ew(l),f=q0(u,l)+BigInt(i)*c;return _o(f,l,e)};S.prototype.log=function(e){let n=e instanceof S?e:new S(e),t=S.precision;S.precision=t+10;try{return this.ln().div(n.ln()).toPrecision(t)}finally{S.precision=t}};S.exp=function(e){return e.exp()};S.ln=function(e){return e.ln()};S.log10=function(e){return e.log(10)};S.log2=function(e){return e.log(2)};S.prototype.sin=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.isZero())return S.ZERO;let e=S.precision,n=Ot(this);if(n<0&&-2*n>=e+4)return this.toPrecision(e);let t=e+15+(n<0?-n:0);if(n+t+30>j0)return S.NAN;let[i,r]=So(this,t),[o]=Fd(i,r);return _o(o,r,e)};S.prototype.cos=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.isZero())return S.ONE;let e=S.precision,n=Ot(this),t=0;for(let i=0;;i++){let r=e+15+t;if(n+r+30>j0)return S.NAN;let[o,s]=So(this,r),[,a]=Fd(o,s);if(a===0n){if(i>=3)return S.ZERO;t+=e+30;continue}let u=J0(a,s);if(u<=t+XN||i>=3)return _o(a,s,e);t=u+5}};S.prototype.tan=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.isZero())return S.ZERO;let e=S.precision,n=Ot(this);if(n<0&&-2*n>=e+4)return this.toPrecision(e);let t=n<0?-n:0,i=0;for(let r=0;;r++){let o=e+15+t+i;if(n+o+30>j0)return S.NAN;let[s,a]=So(this,o),[u,l]=Fd(s,a);if(l===0n){if(r>=3)return u>0n?S.POSITIVE_INFINITY:S.NEGATIVE_INFINITY;i+=e+30;continue}let c=Math.max(u===0n?0:J0(u,a),J0(l,a));if(c<=i+XN||r>=3){let f=(u<<BigInt(a))/l;return _o(f,a,e)}i=c+5}};S.prototype.atan=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite()){let s=S.PI.div(S.TWO);return this.significand>0n?s:s.neg()}let e=S.precision,n=Ot(this);if(n<0&&-2*n>=e+4)return this.toPrecision(e);let t=e+15+(n<0?-n:0),[i,r]=So(this,t),o=Rc(i,r);return _o(o,r,e)};S.prototype.asin=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.isZero())return S.ZERO;let e=this.abs(),n=S.ONE;if(e.gt(n))return S.NAN;if(e.eq(n)){let d=S.PI.div(S.TWO);return this.significand>0n?d:d.neg()}let t=S.precision,i=Ot(this);if(i<0&&-2*i>=t+4)return this.toPrecision(t);let r=t+20+(i<0?-i:0),[o,s]=So(this,r),a=1n<<BigInt(s),u=qN(o,o,s),l=a-u,c=Od(l,s),f=VN(o,c,s),p=Rc(f,s);return _o(p,s,t)};S.prototype.acos=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.abs().gt(S.ONE))return S.NAN;if(this.eq(1))return S.ZERO;if(this.eq(-1))return S.PI;let n=S.precision,t=S.precision;S.precision=n+10;try{let i=S.TWO;if(this.significand>=0n){let o=S.ONE.sub(this).mulToPrecision(S.HALF,n+10).sqrt();return i.mulToPrecision(o.asin(),n)}let r=S.ONE.add(this).mulToPrecision(S.HALF,n+10).sqrt();return S.PI.sub(i.mul(r.asin())).toPrecision(n)}finally{S.precision=t}};S.sin=function(e){return e.sin()};S.cos=function(e){return e.cos()};S.tan=function(e){return e.tan()};S.asin=function(e){return e.asin()};S.acos=function(e){return e.acos()};S.atan=function(e){return e.atan()};S.atan2=function(e,n){let t=e instanceof S?e:new S(e);if(t.isNaN()||n.isNaN())return S.NAN;let i=S.PI,r=i.div(S.TWO);if(n.isZero())return t.isZero()?S.ZERO:t.significand>0n?r:r.neg();let o=t.div(n);return n.significand>0n?o.atan():t.significand>=0n?o.atan().add(i):o.atan().sub(i)};S.prototype.sinh=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NEGATIVE_INFINITY;let e=S.precision,n=Ot(this);if(n<0){if(-2*n>=e+4)return this.toPrecision(e);let r=S.precision;S.precision=e-n+5;try{let o=this.exp();return o.sub(o.inv()).mulToPrecision(S.HALF,e)}finally{S.precision=r}}if(Math.abs(this.toNumber())>1.16*(e+3)){let r=this.abs().exp().div(S.TWO);return this.significand>0n?r:r.neg()}let t=this.exp(),i=t.inv();return t.sub(i).div(S.TWO)};S.prototype.cosh=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ONE;if(!this.isFinite())return S.POSITIVE_INFINITY;let e=S.precision;if(Math.abs(this.toNumber())>1.16*(e+3))return this.abs().exp().div(S.TWO);let n=this.exp(),t=n.inv();return n.add(t).div(S.TWO)};S.prototype.tanh=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.ONE:S.NEGATIVE_ONE;let e=S.precision,n=Ot(this);if(n<0){if(-2*n>=e+4)return this.toPrecision(e);let i=S.precision;S.precision=e-n+5;try{let r=this.mul(S.TWO).exp();return r.sub(S.ONE).div(r.add(S.ONE)).toPrecision(e)}finally{S.precision=i}}if(Math.abs(this.toNumber())>1.16*(e+3))return this.significand>0n?S.ONE:S.NEGATIVE_ONE;let t=this.mul(S.TWO).exp();return t.sub(S.ONE).div(t.add(S.ONE))};S.sinh=function(e){return e.sinh()};S.cosh=function(e){return e.cosh()};S.tanh=function(e){return e.tanh()};S.prototype.expm1=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NEGATIVE_ONE;if(this.isZero())return S.ZERO;let e=S.precision,n=Ot(this);if(n<0&&-n>=e+2)return this.toPrecision(e);if(n<0){let t=S.precision;S.precision=e-n+5;try{return this.exp().sub(S.ONE).toPrecision(e)}finally{S.precision=t}}return this.exp().sub(S.ONE)};S.prototype.log1p=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NAN;if(this.isZero())return S.ZERO;let e=S.ONE.add(this);if(e.isZero())return S.NEGATIVE_INFINITY;if(e.significand<0n)return S.NAN;let n=S.precision,t=Ot(this);if(t<0&&-t>=n+2)return this.toPrecision(n);if(t<0){let i=S.precision;S.precision=n-t+5;try{return S.ONE.add(this).ln().toPrecision(n)}finally{S.precision=i}}return S.ONE.add(this).ln()};S.prototype.asinh=function(){if(this.isNaN())return S.NAN;if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NEGATIVE_INFINITY;let e=this.significand<0n,n=this.abs(),t=S.precision,i=Ot(this);if(i<0&&-2*i>=t+4)return this.toPrecision(t);let r=()=>n.add(n.mul(n).add(S.ONE).sqrt()).ln(),o;if(i<0){let s=S.precision;S.precision=t-i+5;try{o=r().toPrecision(t)}finally{S.precision=s}}else o=r();return e?o.neg():o};S.prototype.acosh=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:S.NAN;if(this.lt(S.ONE))return S.NAN;if(this.eq(1))return S.ZERO;let e=this.sub(S.ONE).div(S.TWO).sqrt();return S.TWO.mul(e.asinh())};S.prototype.atanh=function(){if(this.isNaN())return S.NAN;if(!this.isFinite())return S.NAN;if(this.isZero())return S.ZERO;let e=this.abs();if(e.eq(1))return this.significand>0n?S.POSITIVE_INFINITY:S.NEGATIVE_INFINITY;if(e.gt(S.ONE))return S.NAN;let n=S.precision,t=Ot(this);if(-2*t>=n+4)return this.toPrecision(n);let i=S.precision;S.precision=n-t+5;try{return S.ONE.add(this).div(S.ONE.sub(this)).ln().mulToPrecision(S.HALF,n)}finally{S.precision=i}};S.prototype.nthRoot=function(e){if(this.isNaN()||!Number.isInteger(e)||e===0)return S.NAN;if(e===1)return this;if(e===2)return this.sqrt();if(e===3)return this.cbrt();if(e<0)return this.nthRoot(-e).inv();if(this.isZero())return S.ZERO;if(!this.isFinite())return this.significand>0n?S.POSITIVE_INFINITY:e%2===0?S.NAN:S.NEGATIVE_INFINITY;if(this.significand<0n)return e%2===0?S.NAN:this.neg().nthRoot(e).neg();let n=S.precision,t=S.precision;S.precision=n+8;try{return S.exp(this.ln().div(new S(e))).toPrecision(n)}finally{S.precision=t}};S.asinh=function(e){return e.asinh()};S.acosh=function(e){return e.acosh()};S.atanh=function(e){return e.atanh()};S.expm1=function(e){return e.expm1()};S.log1p=function(e){return e.log1p()};S.nthRoot=function(e,n){return e.nthRoot(n)};function QN(e){let n=vo(e);if(n<=1023){let u=Math.cbrt(Number(e));if(Number.isFinite(u)&&u>=1)return BigInt(Math.floor(u))}let t=n-51,i=Number(e>>BigInt(t)),r=Math.cbrt(i),o=Math.floor(t/3),s=t%3;s===1&&(r*=1.2599210498948732),s===2&&(r*=1.5874010519681994);let a=BigInt(Math.round(r))<<BigInt(o);return a>0n?a:1n}var Su=["number","finite_number","complex","finite_complex","imaginary","real","finite_real","rational","finite_rational","integer","finite_integer","non_finite_number"],z0=["indexed_collection","list","tuple"],$d=[...z0,"collection","set","record","dictionary"],qd=["scalar",...Su,"boolean","string"],G0=["value","color",...$d,...qd],U0=["expression","symbol","function",...G0],Z0=["any","unknown","nothing","never","error",...U0],_u=new Set(Su),nw=new Set($d),tw=new Set(qd),pa=new Set(Z0);function iw(e){return typeof e!="string"?!1:pa.has(e)}function No(e){return typeof e=="string"?pa.has(e):typeof e!="object"||!("kind"in e)?!1:e.kind==="signature"||e.kind==="union"||e.kind==="intersection"||e.kind==="negation"||e.kind==="value"||e.kind==="tuple"||e.kind==="list"||e.kind==="record"||e.kind==="dictionary"||e.kind==="set"||e.kind==="broadcastable"||e.kind==="symbol"||e.kind==="expression"||e.kind==="numeric"||e.kind==="collection"||e.kind==="indexed_collection"||e.kind==="reference"}var Vd=class{input;pos=0;line=1;column=1;tokens=[];tolerant;constructor(n,t){this.input=n,this.tolerant=t?.tolerant??!1}saveState(){return{pos:this.pos,line:this.line,column:this.column,tokens:[...this.tokens]}}restoreState(n){this.pos=n.pos,this.line=n.line,this.column=n.column,this.tokens=n.tokens}error(n){throw new Error(`Lexer error at line ${this.line}, column ${this.column}: ${n}`)}peek(n=0){let t=this.pos+n;return t<this.input.length?this.input[t]:""}advance(){let n=this.input[this.pos++];return n===`
|
|
@@ -45,7 +45,7 @@ Type-style membership works with:
|
|
|
45
45
|
64387206238513712392736304998503539223928787979063
|
|
46
46
|
36440323547845358519277777872709060830319943013323
|
|
47
47
|
16712476158709792455479119092126201854803963934243
|
|
48
|
-
`}},EulerGamma:{description:"The Euler\u2013Mascheroni constant \u03B3 \u2248 0.5772.",keywords:["euler-mascheroni","euler gamma"],type:"finite_real",wikidata:"Q273023",holdUntil:"N",isConstant:!0,value:e=>e.number(en(e)?S.EULER_GAMMA:.5772156649015329)}},{PreIncrement:{description:"Increment a number by one.",signature:"(number) -> number"},PreDecrement:{description:"Decrement a number by one.",signature:"(number) -> number"}},{IsPrime:{description:"`IsPrime(n)` returns `True` if `n` is a prime number",wikidata:"Q49008",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",evaluate:([e],{engine:n})=>{let t=fp(e);if(t!==void 0)return n.symbol(t?"True":"False")}},IsComposite:{description:"`IsComposite(n)` returns `True` if `n` is not a prime number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",canonical:(e,{engine:n})=>n.expr(["Not",["IsPrime",...e]])},IsOdd:{description:"`IsOdd(n)` returns `True` if `n` is an odd number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",evaluate:(e,{engine:n})=>{let t=!1,i=e.every(r=>{if(r.im!==0)return!1;let o=jt(r);if(o!==null)return o%BigInt(2)!==BigInt(0);let s=r.re;return Number.isInteger(s)?s%2!==0:(t=!0,!1)});if(!t)return n.symbol(i?"True":"False")}},IsEven:{description:"Even Number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",canonical:(e,{engine:n})=>n.expr(["Not",["IsOdd",...e]])}},{GCD:{description:"Greatest Common Divisor",complexity:1200,broadcastable:!1,signature:"(any*) -> number",type:e=>e.every(n=>n.isInteger)?"finite_integer":"number",sgn:e=>{if(e.every(n=>n.isInteger))return e.some(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"})?"positive":"non-negative"},evaluate:(e,{engine:n})=>{if(!e.every(t=>t.isInteger)){let t=iC(e);if(t!==void 0)return t}return wA(n,e,"GCD")}},LCM:{description:"Least Common Multiple",complexity:1200,broadcastable:!1,signature:"(any*) -> number",type:e=>e.every(n=>n.isInteger)?"finite_integer":"number",sgn:e=>{if(e.every(n=>n.isInteger))return e.every(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"})?"positive":e.some(n=>n.isSame(0))?"zero":"non-negative"},evaluate:(e,{engine:n})=>wA(n,e,"LCM")},Numerator:{description:"Numerator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> number | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];return(t.operator==="Rational"||t.operator==="Divide")&&m(t)?t.op1:n._fn("Numerator",Ji(n,e))},sgn:([e])=>e.sgn,evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?i.op1.evaluate():i.numerator}},Denominator:{description:"Denominator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> number | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];if((t.operator==="Rational"||t.operator==="Divide")&&m(t))return t.op2;let i=Ie(t);return i!==void 0?n.number(i[1]):n._fn("Denominator",Ji(n,e))},sgn:()=>"positive",evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?i.op2.evaluate():i.denominator}},NumeratorDenominator:{description:"Sequence of Numerator and Denominator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> tuple<number, number> | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];if((t.operator==="Rational"||t.operator==="Divide")&&m(t))return n.tuple(...t.ops);let i=Ie(t.evaluate());return i!==void 0?n.tuple(n.number(i[0]),n.number(i[1])):n._fn("NumeratorDenominator",e.map(r=>r.evaluate()))},evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?t.tuple(...i.ops):t.tuple(...i.numeratorDenominator)}}},{Max:{description:"Maximum of two or more numbers",complexity:1200,broadcastable:!1,signature:"(value*) -> number | list",sgn:e=>{if(e.some(n=>n.isReal==!1||n.isNaN))return"unsigned";if(!e.some(n=>n.isReal==!1||n.isNaN!==!1)){if(e.some(n=>n.isPositive))return"positive";if(e.every(n=>n.isNonPositive))return e.some(n=>n.isSame(0))?"zero":"non-positive";if(e.some(n=>n.isNonNegative))return"non-negative";if(e.every(n=>n.isNegative))return"negative";if(e.every(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"}))return"not-zero"}},evaluate:(e,{engine:n})=>ch(n,e,"Max")},Min:{description:"Minimum of two or more numbers",complexity:1200,broadcastable:!1,signature:"(value+) -> number | list",sgn:e=>{if(e.some(n=>n.isReal==!1||n.isNaN))return"unsigned";if(!e.some(n=>n.isReal==!1||n.isNaN!==!1)){if(e.some(n=>n.isNegative))return"negative";if(e.every(n=>n.isNonNegative))return e.some(n=>n.isSame(0))?"zero":"non-negative";if(e.some(n=>n.isNonPositive))return"non-positive";if(e.every(n=>n.isPositive))return"positive"}},evaluate:(e,{engine:n})=>ch(n,e,"Min")},ElementMax:{description:"Element-wise maximum: broadcasts scalars over collections (and zips collections), returning a collection; all-scalar arguments give a scalar. Variadic.",complexity:1200,broadcastable:!0,signature:"(number, number+) -> number",type:e=>He(e),evaluate:(e,{numericApproximation:n})=>NA(e,!0,n===!0)},ElementMin:{description:"Element-wise minimum: broadcasts scalars over collections (and zips collections), returning a collection; all-scalar arguments give a scalar. Variadic.",complexity:1200,broadcastable:!0,signature:"(number, number+) -> number",type:e=>He(e),evaluate:(e,{numericApproximation:n})=>NA(e,!1,n===!0)},Clamp:{description:"Clamp a value to the range [lo, hi] = min(max(x, lo), hi). Broadcasts over collection arguments.",complexity:1200,broadcastable:!0,signature:"(number, number, number) -> number",type:e=>He(e),evaluate:([e,n,t],{numericApproximation:i})=>{let r=IE(e,n,!0,!1);if(r!==void 0)return IE(r,t,!1,i===!0)}},Supremum:{description:"Like Max, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number | list",evaluate:(e,{engine:n})=>ch(n,e,"Supremum")},Infimum:{description:"Like Min, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number | list",evaluate:(e,{engine:n})=>ch(n,e,"Infimum")},Distance:{description:"Euclidean distance between two points (tuples of numbers).",complexity:6e3,signature:"(tuple, tuple) -> number",evaluate:([e,n],{engine:t,numericApproximation:i})=>{if(!m(e)||!m(n)||e.operator!=="Tuple"||n.operator!=="Tuple"||e.ops.length!==n.ops.length||e.ops.length===0)return t.error("incompatible-type");let r=[];for(let o=0;o<e.ops.length;o++){let s=e.ops[o],a=n.ops[o];if(!N(s)||!N(a)||s.isFinite===!1||a.isFinite===!1)return t.error("expected-value");r.push(t.function("Power",[t.function("Subtract",[s,a]),t.number(2)]))}return t.function("Sqrt",[t.function("Add",r)]).evaluate({numericApproximation:i})}},Product:{description:"`Product(f, a, b)` computes the product of `f` from `a` to `b`",wikidata:"Q901718",complexity:1e3,broadcastable:!1,scoped:!0,lazy:!0,signature:"((number+) -> number, (tuple<integer>|tuple<integer, integer>)+) -> number",type:vE,canonical:([e,...n],{scope:t})=>gE("Product",e,n,t),evaluate:(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1),o=yp(e[0],r,t);if(o==="symbolic")return r.length===1?cE(e[0],r[0],t):void 0;if(o==="numeric"&&!i)return r.length===1?pE(e[0],r[0],t):void 0;if(o==="numeric"&&i&&r.length===1){let a=mE(e[0],r[0],t);if(a!==void 0)return a}let s=St(Ep(e[0],r,(a,u)=>{let l=u.evaluate({numericApproximation:i});return wE(a,l)??a.mul(l)},t.One),t._timeRemaining);if(s!==Xo)return s?.evaluate({numericApproximation:i})??t.NaN},evaluateAsync:async(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1);{let s=yp(e[0],r,t);if(s==="symbolic")return r.length===1?cE(e[0],r[0],t):void 0;if(s==="numeric"&&!i)return r.length===1?pE(e[0],r[0],t):void 0;if(s==="numeric"&&i&&r.length===1){let a=mE(e[0],r[0],t);if(a!==void 0)return a}}let o=await da(Ep(e[0],r,(s,a)=>{let u=a.evaluate({numericApproximation:i});return wE(s,u)??s.mul(u)},t.One),t._timeRemaining,n.signal);if(o!==Xo)return o?.evaluate({numericApproximation:i})??t.NaN}},Sum:{description:"`Sum(f, [a, b])` computes the sum of `f` from `a` to `b`; `Sum(L)` sums the elements of a collection `L`",keywords:["summation","sigma"],wikidata:"Q218005",complexity:1e3,broadcastable:!1,scoped:!0,lazy:!0,signature:"(any, tuple*) -> number",type:vE,canonical:([e,...n],{scope:t,engine:i})=>{if(n.length===0){let r=e?.canonical;if(r?.isCollection)return i._fn("Sum",[r])}return gE("Sum",e,n,t)},evaluate:([e,...n],{engine:t,numericApproximation:i})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Ko(e)?void 0:St(_A(e,t.Zero,(u,l)=>lh(u,l.evaluate({numericApproximation:i}),i)),t._timeRemaining)?.evaluate({numericApproximation:i})??t.NaN;let r=i,o=yp(e,n,t);if(o==="symbolic")return n.length===1?lE(e,n[0],t):void 0;if(o==="numeric"&&!r)return n.length===1?fE(e,n[0],t):void 0;if(o==="numeric"&&r&&n.length===1){let a=dE(e,n[0],t);if(a!==void 0)return a}let s=St(Ep(e,n,(a,u)=>lh(a,u.evaluate({numericApproximation:r}),r),t.Zero),t._timeRemaining);if(s!==Xo)return s?.evaluate({numericApproximation:r})??t.NaN},evaluateAsync:async([e,...n],{engine:t,signal:i,numericApproximation:r})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Ko(e)?void 0:(await da(_A(e,t.Zero,(u,l)=>lh(u,l.evaluate({numericApproximation:r}),r)),t._timeRemaining,i))?.evaluate({numericApproximation:r})??t.NaN;let o=r;{let a=yp(e,n,t);if(a==="symbolic")return n.length===1?lE(e,n[0],t):void 0;if(a==="numeric"&&!o)return n.length===1?fE(e,n[0],t):void 0;if(a==="numeric"&&o&&n.length===1){let u=dE(e,n[0],t);if(u!==void 0)return u}}let s=await da(Ep(e,n,(a,u)=>lh(a,u.evaluate({numericApproximation:o}),o),t.Zero),t._timeRemaining,i);if(s!==Xo)return s?.evaluate({numericApproximation:o})??t.NaN}},Interpret:{description:"Interpret a notational expression as its mathematical meaning. In v1: a continuation-bearing `Add`/`Multiply` (e.g. `1 + 2 + \\dots + n`) becomes a `Sum`/`Product`. Returns the argument unchanged when the (strict) inference gate does not pass",complexity:9e3,broadcastable:!1,lazy:!0,signature:"(any) -> any",evaluate:([e])=>{if(e)return Np(e)??e}}}];function SA(e,n,t){if(t>100)return;let i=e.One;for(let o=0;o<t;o++){let s=n.add(o);if(s.isSame(0))return e.ComplexInfinity;i=i.mul(s)}let r=1n;for(let o=2;o<t;o++)r*=BigInt(o);return e.number(r).div(i)}function wE(e,n){if(e.operator==="Error")return e;if(q(n))return e.engine.typeError("number",n.type)}function lh(e,n,t){let i=wE(e,n);if(i)return i;let r=e.add(n);return t?r:N(e)&&e.isExact&&N(n)&&n.isExact&&N(r)&&!r.isExact?e.engine.function("Add",[e,n]):r}function*_A(e,n,t){let i=n;for(let r of e.each())i=t(i,r),yield i;return i}function lV(e,n){let t=e.engine;if(N(e)){let i=e.numericValue;if(typeof i=="number")return t.number(Math.abs(i));if(i.im!==0){let r=i.re,o=i.im,s=r*r+o*o;if(Number.isInteger(r)&&Number.isInteger(o)&&Number.isSafeInteger(s))return t.function("Sqrt",[t.number(s)]).evaluate({numericApproximation:n})}return t.number(i.abs())}if(e.isNonNegative)return e;if(e.isNegative)return e.neg();if(e.unknowns.length===0){let i=e.N(),r=i.re,o=i.im;if(Number.isFinite(r)&&Number.isFinite(o)&&o!==0){let s=Pl(e);if(s){let[a,u]=s,l=t.function("Add",[t.function("Multiply",[a,a]),t.function("Multiply",[u,u])]),c=Pe(l).evaluate();if(N(c)&&c.im===0&&c.isNonNegative===!0){let f=r*r+o*o,p=c.re;if(Number.isFinite(p)&&Math.abs(p-f)<=1e-10*(1+Math.abs(f)))return t.function("Sqrt",[c]).evaluate({numericApproximation:n})}}}}}function Pl(e){let n=e.engine;if(N(e)){let t=e.json;return Array.isArray(t)&&t[0]==="Complex"?[n.box(t[1]),n.box(t[2])]:[e,n.Zero]}if(m(e)){let t=e.operator;if(t==="Add"){let i=[],r=[];for(let o of e.ops){let s=Pl(o);if(!s)return;i.push(s[0]),r.push(s[1])}return[n.function("Add",i),n.function("Add",r)]}if(t==="Negate"){let i=Pl(e.op1);return i?[i[0].neg(),i[1].neg()]:void 0}if(t==="Subtract"){let i=Pl(e.op1),r=Pl(e.op2);return!i||!r?void 0:[n.function("Subtract",[i[0],r[0]]),n.function("Subtract",[i[1],r[1]])]}if(t==="Multiply"){let i=n.One,r=n.Zero;for(let o of e.ops){let s=Pl(o);if(!s)return;let[a,u]=s,l=n.function("Subtract",[n.function("Multiply",[i,a]),n.function("Multiply",[r,u])]),c=n.function("Add",[n.function("Multiply",[i,u]),n.function("Multiply",[r,a])]);i=l,r=c}return[i,r]}if(t==="Complex")return[e.op1,e.op2]}return[e,n.Zero]}function TA(e,n){let t=e.engine,i=n==="Max"||n==="Supremum";if(m(e,"Interval")){let r=i?e.op2:e.op1;return!r.isNumber||!N(r)?[void 0,[e]]:[r,[]]}if(e.operator==="Range"){if(Yr(e))return[void 0,[e]];if(i){let r=ji(e),o=Jk(r);return[t.number(Math.max(r[0],o)),[]]}else return[t.number(ji(e)[0]),[]]}if(m(e,"Linspace"))return e.nops===1?e=i?e.op1:t.One:i?e=e.op2:e=e.op1,[e,[]];if(e.isCollection){if(e.isFiniteCollection!==!0||Ko(e))return[void 0,[e]];let r,o=[];for(let s of e.each()){let[a,u]=TA(s,n);if(a){if(a.isNaN)return[t.NaN,[]];a.im!==0?o.push(a):r?(i&&a.isGreater(r)||!i&&a.isLess(r))&&(r=a):r=a}o.push(...u)}return[r,o]}return!e.isNumber||!N(e)?[void 0,[e]]:[e,[]]}function IE(e,n,t,i){let r=e.engine;if(e.isNaN===!0||n.isNaN===!0)return r.NaN;if(N(e)&&e.im!==0||N(n)&&n.im!==0)return;let o=t?n.isGreater(e):n.isLess(e);if(o===void 0)return;let s=o?n:e;return i?s.N():s}function NA(e,n,t){if(e.length===0)return;let i=e[0];for(let r=1;r<e.length;r++){let o=IE(i,e[r],n,!1);if(o===void 0)return;i=o}return t?i.N():i}function ch(e,n,t){let i=t==="Max"||t==="Supremum";if(n=we(n),n.length===0)return i?e.NegativeInfinity:e.PositiveInfinity;let r,o=[];for(let s of n){let[a,u]=TA(s,t);if(a){if(a.isNaN)return e.NaN;a.im!==0?o.push(a):r?(i&&a.isGreater(r)||!i&&a.isLess(r))&&(r=a):r=a}o.push(...u)}return o.length>0?e.expr(r?[t,r,...o]:[t,...o]):r??(i?e.NegativeInfinity:e.PositiveInfinity)}function wA(e,n,t){let i=t==="LCM"?ma:Dn,r=t==="LCM"?$M:Y1;if(n.length===0)return t==="LCM"?e.One:e.Zero;if(n.some(a=>a.isCollection)){let a=!0,u=[...n];for(;a&&u.some(l=>l.isCollection);){let l=[];for(let c of u)if(c.isCollection){if(c.isFiniteCollection!==!0||Ko(c)){a=!1;break}for(let f of c.each())l.push(f)}else l.push(c);a&&(u=l)}if(a){if(u.length===0)return t==="LCM"?e.One:e.Zero;n=u}}if(n.length>0&&n.some(a=>N(a)&&!a.isExact)&&n.every(a=>N(a)&&Number.isFinite(a.re)&&!a.im)){let a=t==="LCM"?Ud:qc,u=Math.abs(n[0].re);for(let l=1;l<n.length;l++)u=a(u,n[l].re);return e.number(u)}let o=[];if(en(e)){let a=null;for(let u of n)if(a===null){let l=J1(u);l!==null&&l.isInteger()?a=l.abs():o.push(u)}else{let l=J1(u);l&&l.isInteger()?a=r(a,l):o.push(u)}return o.length===0?a===null?e.One:e.number(a):a===null?e._fn(t,o):e._fn(t,[e.number(a),...o])}let s=null;for(let a of n)s===null?a.isInteger?s=Math.abs(a.re):o.push(a):a.isInteger?s=i(s,a.re):o.push(a);return o.length===0?s===null?e.One:e.number(s):s===null?e._fn(t,o):e._fn(t,[e.number(s),...o])}var cV=new Set(["Negate","Add","Subtract","Multiply","Divide","Square","Exp","Power"]),fV=new Map([["Multiply",["Divide"]],["Divide",["Power"]],["Root",["Power"]]]),pV=8,MA=new WeakMap;function TE(e,n,t=pV){if(e.length<t)return;let i=MA.get(e);return(i===void 0||i.count!==e.length)&&(i={count:e.length},MA.set(e,i)),n?i.variations??=CA(e,!0):i.plain??=CA(e,!1)}function CA(e,n){let t=new Map,i=[],r=(o,s)=>{let a=t.get(o);a?a.push(s):t.set(o,[s])};for(let o=0;o<e.length;o++){let s=e[o],a={rule:s,ordinal:o};if(s.operators!==void 0&&s.operators.length>0){for(let f of s.operators)r(f,a);continue}let u=s.match;if(u===void 0){i.push(a);continue}if(!m(u)){i.push(a);continue}let l=u.operator;if(l.startsWith("_")){i.push(a);continue}if((s.useVariations??n)&&cV.has(l)){i.push(a);continue}r(l,a)}return{byHead:t,alwaysTry:i,count:e.length}}function dV(e,n){let t=0,i=e.length;for(;t<i;){let r=t+i>>1;e[r].ordinal>n?i=r:t=r+1}return t}function*fh(e,n,t){let i=[];e.alwaysTry.length>0&&i.push(e.alwaysTry);let r=n.operator,o=e.byHead.get(r);o!==void 0&&i.push(o);let s=fV.get(r);if(s!==void 0)for(let l of s){let c=e.byHead.get(l);c!==void 0&&i.push(c)}if(N(n)){let l=e.byHead.get("Divide");l!==void 0&&i.push(l)}let a=i.map(l=>dV(l,t)),u=-1;for(;;){let l=-1,c=1/0;for(let p=0;p<i.length;p++)if(a[p]<i[p].length){let d=i[p][a[p]].ordinal;d<c&&(c=d,l=p)}if(l<0)return;let f=i[l][a[l]++];f.ordinal!==u&&(u=f.ordinal,yield f)}}function kA(e){return e.match===void 0&&typeof e.replace=="function"&&e.condition===void 0&&e.useVariations!==!0&&e.operators!==void 0&&e.operators.length===1}var mV={};function gV(e,n){let t=n.map(o=>o.replace),i=t.length;return{_tag:"boxed-rule",match:void 0,replace:o=>{let s=o,a;for(let u=0;u<i;u++){let l=t[u](s,mV);if(l!=null&&"because"in l){let c=l;s=c.value,a=c}}return a},condition:void 0,operators:[e],id:`hot-head-dispatch:${e}`}}function AA(e){let n=new Map;for(let o of e){if(!kA(o))continue;let s=o.operators[0],a=n.get(s);a?a.push(o):n.set(s,[o])}let t=new Map;for(let[o,s]of n)s.length>=2&&t.set(o,gV(o,s));if(t.size===0)return e;let i=new Set,r=[];for(let o of e){if(kA(o)){let s=o.operators[0],a=t.get(s);if(a!==void 0){i.has(s)||(i.add(s),r.push(a));continue}}r.push(o)}return r}var RA=new WeakSet;var FA={boolean:e=>e.type.matches("boolean"),string:e=>q(e),number:e=>N(e),symbol:e=>w(e),expression:e=>!0,numeric:e=>{let[n,t]=e.toNumericValue();return t.isSame(1)},integer:e=>e.isInteger,rational:e=>e.isRational,irrational:e=>e.isReal===!0&&e.isRational===!1,real:e=>e.isReal,notreal:e=>e.isReal===!1,complex:e=>e.type.matches("complex"),imaginary:e=>e.type.matches("imaginary"),positive:e=>e.isPositive,negative:e=>e.isNegative,nonnegative:e=>e.isNonNegative,nonpositive:e=>e.isNonPositive,even:e=>e.isEven,odd:e=>e.isOdd,prime:e=>fp(e)===!0,composite:e=>e.isInteger===!0&&e.isPositive===!0&&e.isEqual(1)===!1&&fp(e)===!1,notzero:e=>e.isEqual(0)===!1,notone:e=>e.isEqual(1)===!1,finite:e=>e.isFinite,infinite:e=>e.isFinite===!1,constant:e=>e.valueDefinition?.isConstant??!1,variable:e=>!(e.valueDefinition?.isConstant??!0),function:e=>e.operatorDefinition!==void 0,relation:e=>mt(e.operator),equation:e=>e.operator==="Equal",inequality:e=>rr(e.operator),collection:e=>e.isCollection,list:e=>e.operator==="List",set:e=>e.operator==="Set",tuple:e=>e.operator==="Tuple"||e.operator==="Single"||e.operator==="Pair"||e.operator==="Triple",single:e=>e.operator==="Single",pair:e=>e.operator==="Pair",triple:e=>e.operator==="Triple",scalar:e=>e.rank===0,tensor:e=>e.rank>0,vector:e=>e.rank===1,matrix:e=>e.rank===2,unit:e=>e.operator==="Unit",dimension:e=>e.operator==="Dimension",angle:e=>e.operator==="Angle",polynomial:e=>e.unknowns.length===1};function BA(e,n){for(let t of n)if(FA[t](e)!==!0)return!1;return!0}function $A(e,n){let t=e._isVerifying;e._isVerifying=!0;try{return w(n.evaluate(),"True")}finally{e._isVerifying=t}}function hV(e){let n=/\\[a-zA-Z]+|[{}]|[\d]+|[+\-*/^_=()><,.;]|[a-zA-Z]/g,t=e.match(n);return t?t.filter(i=>!/^[ \f\n\r\t\v\xA0\u2028\u2029]+$/.test(i)):[]}function bV(e){let n=e.peek,t=null;if(n==="\\mathrm")e.nextToken(),t=e.parseStringGroup();else if(/^[a-z]$/.test(n))for(t=e.nextToken();/^[a-z]$/.test(e.peek);)t+=e.nextToken();else{let i={">0":"positive","\\gt0":"positive","<0":"negative","\\lt0":"negative",">=0":"nonnegative","\\geq0":"nonnegative","<=0":"nonpositive","\\leq0":"nonpositive","!=0":"notzero","\\neq0":"notzero","\\neq1":"notone","!=1":"notone","\\in\\R":"real","\\in\\mathbb{R}":"real","\\in\\C":"complex","\\in\\mathbb{C}":"complex","\\in\\Q":"rational","\\in\\mathbb{Q}":"rational","\\in\\Z^+":"integer,positive","\\in\\Z^-":"integer,negative","\\in\\Z^*":"integer,notzero","\\in\\R^+":"positive","\\in\\R^-":"negative","\\in\\R^*":"real,notzero","\\in\\Z":"integer","\\in\\mathbb{Z}":"integer","\\in\\N":"integer,nonnegative","\\in\\mathbb{N}":"integer,nonnegative","\\in\\N^*":"integer,positive","\\in\\N_0":"integer,nonnegative","\\in\\R\\backslash\\Q":"irrational"};for(let r in i)if(e.matchAll(hV(r))){t=i[r];break}}if(!t)return null;for(let i of t.split(","))if(!Object.keys(FA).includes(i))throw new Error(`Unexpected condition "${i}" in a rule`);return t}function PA(e){let n=[];do{let t=bV(e);if(!t)break;n.push(t)}while(e.match(","));return n.join(",")}function ME(e){let n=null;if(e.match(":"))n=PA(e);else if(e.matchAll(["_","<{>"])&&(n=PA(e),!e.match("<}>")))return null;return n}function yV(e){return w(e,"e")?e.engine.symbol("ExponentialE",{canonical:!1}):w(e,"i")?e.engine.I:e}function ph(e){return e.map(yV,{canonical:!1})}function xV(e){if(m(e,"InvisibleOperator")&&w(e.ops[0],"_")){let n=e.ops.slice(1);if(n.length>0&&n.every(t=>w(t)))return e.engine.symbol("_"+n.map(t=>t.symbol).join(""))}return m(e,"Subscript")&&w(e.op1,"_")&&w(e.op2)?e.engine.symbol("__"+e.op2.symbol):e}function DA(e,n,t){if(n===void 0||typeof n=="function")return;if(typeof n=="string"){let r=e.parse(n,{form:t?.canonical?"canonical":"raw"})??e.expr("Nothing");return r=ph(r),r=r.map(xV,{canonical:!1}),t?.autoWildcard&&(r=r.map(o=>w(o)&&o.symbol.length===1?e.symbol("_"+o.symbol):o,{canonical:!1})),r}let i=t?.canonical??(n instanceof Je?n.isCanonical:!1);return e.expr(n,{form:i?"canonical":"raw"})}function EV(e,n,t){let i=p=>({kind:"symbol",latexTrigger:p,parse:(d,g)=>{r[p]||(r[p]=`_${p}`);let h=ME(d);return h!==null&&(o[p]?o[p]+=","+h:o[p]=h),r[p]}}),r={},o={},s=[...Aa,{kind:"prefix",precedence:100,latexTrigger:"...",parse:(p,d)=>{let g=p.nextToken();if(!"abcfghjklmnopqrstuvwxyz".includes(g))return null;let h="__";if(p.match("?")&&(h="___"),r[g]&&r[g]!==`${h}${g}`)throw new Error(`Duplicate wildcard "${g}"`);r[g]||(r[g]=`${h}${g}`);let b=ME(p);return b===null?`${h}${g}`:(o[g]?o[g]+=","+b:o[g]=b,`${h}${g}`)}},..."abcfghjklmnopqrstuvwxyz".split("").map(i),{kind:"infix",precedence:100,latexTrigger:"->",parse:(p,d,g)=>{let h=p.parseExpression({...g,minPrec:20});if(h===null)return null;let b=null;if(p.match(";")){let E=!1,v=p.index;do{p.skipSpace();let _=p.nextToken();if(r[_]){let I=ME(p);if(I===null||!I){E=!0,p.index=v;break}o[_]?o[_]+=","+I:o[_]=I}}while(!E&&!p.atEnd);b=p.parseExpression(g)}let y=[];for(let E in o){let v=o[E].split(",");v.length!==0&&(v.length===1?y.push(["Condition",r[E],v[0]]):y.push(["Condition",r[E],["And",...v]]))}let x;return b&&y.length>0?x=["And",b,...y]:b?x=b:y.length===1?x=y[0]:y.length>1&&(x=["And",...y]),x?["Rule",d,h,x]:["Rule",d,h]}}],a=t?.canonical??!1,u=e._requireLatexSyntax().constructor,l=new u({dictionary:s}),c=e.contextStack[0]?.lexicalScope;c&&e.pushScope({parent:c,bindings:new Map});let f;try{if(f=e.expr(l.parse(n)??"Nothing"),!f.isValid||f.operator!=="Rule")throw new Error(`Invalid rule "${n}"
|
|
48
|
+
`}},EulerGamma:{description:"The Euler\u2013Mascheroni constant \u03B3 \u2248 0.5772.",keywords:["euler-mascheroni","euler gamma"],type:"finite_real",wikidata:"Q273023",holdUntil:"N",isConstant:!0,value:e=>e.number(en(e)?S.EULER_GAMMA:.5772156649015329)}},{PreIncrement:{description:"Increment a number by one.",signature:"(number) -> number"},PreDecrement:{description:"Decrement a number by one.",signature:"(number) -> number"}},{IsPrime:{description:"`IsPrime(n)` returns `True` if `n` is a prime number",wikidata:"Q49008",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",evaluate:([e],{engine:n})=>{let t=fp(e);if(t!==void 0)return n.symbol(t?"True":"False")}},IsComposite:{description:"`IsComposite(n)` returns `True` if `n` is not a prime number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",canonical:(e,{engine:n})=>n.expr(["Not",["IsPrime",...e]])},IsOdd:{description:"`IsOdd(n)` returns `True` if `n` is an odd number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",evaluate:(e,{engine:n})=>{let t=!1,i=e.every(r=>{if(r.im!==0)return!1;let o=jt(r);if(o!==null)return o%BigInt(2)!==BigInt(0);let s=r.re;return Number.isInteger(s)?s%2!==0:(t=!0,!1)});if(!t)return n.symbol(i?"True":"False")}},IsEven:{description:"Even Number",complexity:1200,broadcastable:!0,signature:"(number) -> boolean",canonical:(e,{engine:n})=>n.expr(["Not",["IsOdd",...e]])}},{GCD:{description:"Greatest Common Divisor",complexity:1200,broadcastable:!1,signature:"(any*) -> number",type:e=>e.every(n=>n.isInteger)?"finite_integer":"number",sgn:e=>{if(e.every(n=>n.isInteger))return e.some(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"})?"positive":"non-negative"},evaluate:(e,{engine:n})=>{if(!e.every(t=>t.isInteger)){let t=iC(e);if(t!==void 0)return t}return wA(n,e,"GCD")}},LCM:{description:"Least Common Multiple",complexity:1200,broadcastable:!1,signature:"(any*) -> number",type:e=>e.every(n=>n.isInteger)?"finite_integer":"number",sgn:e=>{if(e.every(n=>n.isInteger))return e.every(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"})?"positive":e.some(n=>n.isSame(0))?"zero":"non-negative"},evaluate:(e,{engine:n})=>wA(n,e,"LCM")},Numerator:{description:"Numerator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> number | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];return(t.operator==="Rational"||t.operator==="Divide")&&m(t)?t.op1:n._fn("Numerator",Ji(n,e))},sgn:([e])=>e.sgn,evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?i.op1.evaluate():i.numerator}},Denominator:{description:"Denominator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> number | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];if((t.operator==="Rational"||t.operator==="Divide")&&m(t))return t.op2;let i=Ie(t);return i!==void 0?n.number(i[1]):n._fn("Denominator",Ji(n,e))},sgn:()=>"positive",evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?i.op2.evaluate():i.denominator}},NumeratorDenominator:{description:"Sequence of Numerator and Denominator of an expression",complexity:1200,broadcastable:!0,lazy:!0,signature:"(number) -> tuple<number, number> | nothing",canonical:(e,{engine:n})=>{if(e.length===0)return n.Nothing;let t=e[0];if((t.operator==="Rational"||t.operator==="Divide")&&m(t))return n.tuple(...t.ops);let i=Ie(t.evaluate());return i!==void 0?n.tuple(n.number(i[0]),n.number(i[1])):n._fn("NumeratorDenominator",e.map(r=>r.evaluate()))},evaluate:(e,{engine:n})=>{let t=n;if(e.length===0)return t.Nothing;let i=e[0];return(i.operator==="Rational"||i.operator==="Divide")&&m(i)?t.tuple(...i.ops):t.tuple(...i.numeratorDenominator)}}},{Max:{description:"Maximum of two or more numbers",complexity:1200,broadcastable:!1,signature:"(value*) -> number",sgn:e=>{if(e.some(n=>n.isReal==!1||n.isNaN))return"unsigned";if(!e.some(n=>n.isReal==!1||n.isNaN!==!1)){if(e.some(n=>n.isPositive))return"positive";if(e.every(n=>n.isNonPositive))return e.some(n=>n.isSame(0))?"zero":"non-positive";if(e.some(n=>n.isNonNegative))return"non-negative";if(e.every(n=>n.isNegative))return"negative";if(e.every(n=>{let t=n.sgn;return t==="positive"||t==="negative"||t==="not-zero"}))return"not-zero"}},evaluate:(e,{engine:n})=>ch(n,e,"Max")},Min:{description:"Minimum of two or more numbers",complexity:1200,broadcastable:!1,signature:"(value+) -> number",sgn:e=>{if(e.some(n=>n.isReal==!1||n.isNaN))return"unsigned";if(!e.some(n=>n.isReal==!1||n.isNaN!==!1)){if(e.some(n=>n.isNegative))return"negative";if(e.every(n=>n.isNonNegative))return e.some(n=>n.isSame(0))?"zero":"non-negative";if(e.some(n=>n.isNonPositive))return"non-positive";if(e.every(n=>n.isPositive))return"positive"}},evaluate:(e,{engine:n})=>ch(n,e,"Min")},ElementMax:{description:"Element-wise maximum: broadcasts scalars over collections (and zips collections), returning a collection; all-scalar arguments give a scalar. Variadic.",complexity:1200,broadcastable:!0,signature:"(number, number+) -> number",type:e=>He(e),evaluate:(e,{numericApproximation:n})=>NA(e,!0,n===!0)},ElementMin:{description:"Element-wise minimum: broadcasts scalars over collections (and zips collections), returning a collection; all-scalar arguments give a scalar. Variadic.",complexity:1200,broadcastable:!0,signature:"(number, number+) -> number",type:e=>He(e),evaluate:(e,{numericApproximation:n})=>NA(e,!1,n===!0)},Clamp:{description:"Clamp a value to the range [lo, hi] = min(max(x, lo), hi). Broadcasts over collection arguments.",complexity:1200,broadcastable:!0,signature:"(number, number, number) -> number",type:e=>He(e),evaluate:([e,n,t],{numericApproximation:i})=>{let r=IE(e,n,!0,!1);if(r!==void 0)return IE(r,t,!1,i===!0)}},Supremum:{description:"Like Max, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number",evaluate:(e,{engine:n})=>ch(n,e,"Supremum")},Infimum:{description:"Like Min, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number",evaluate:(e,{engine:n})=>ch(n,e,"Infimum")},Distance:{description:"Euclidean distance between two points (tuples of numbers).",complexity:6e3,signature:"(tuple, tuple) -> number",evaluate:([e,n],{engine:t,numericApproximation:i})=>{if(!m(e)||!m(n)||e.operator!=="Tuple"||n.operator!=="Tuple"||e.ops.length!==n.ops.length||e.ops.length===0)return t.error("incompatible-type");let r=[];for(let o=0;o<e.ops.length;o++){let s=e.ops[o],a=n.ops[o];if(!N(s)||!N(a)||s.isFinite===!1||a.isFinite===!1)return t.error("expected-value");r.push(t.function("Power",[t.function("Subtract",[s,a]),t.number(2)]))}return t.function("Sqrt",[t.function("Add",r)]).evaluate({numericApproximation:i})}},Product:{description:"`Product(f, a, b)` computes the product of `f` from `a` to `b`",wikidata:"Q901718",complexity:1e3,broadcastable:!1,scoped:!0,lazy:!0,signature:"((number+) -> number, (tuple<integer>|tuple<integer, integer>)+) -> number",type:vE,canonical:([e,...n],{scope:t})=>gE("Product",e,n,t),evaluate:(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1),o=yp(e[0],r,t);if(o==="symbolic")return r.length===1?cE(e[0],r[0],t):void 0;if(o==="numeric"&&!i)return r.length===1?pE(e[0],r[0],t):void 0;if(o==="numeric"&&i&&r.length===1){let a=mE(e[0],r[0],t);if(a!==void 0)return a}let s=St(Ep(e[0],r,(a,u)=>{let l=u.evaluate({numericApproximation:i});return wE(a,l)??a.mul(l)},t.One),t._timeRemaining);if(s!==Xo)return s?.evaluate({numericApproximation:i})??t.NaN},evaluateAsync:async(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1);{let s=yp(e[0],r,t);if(s==="symbolic")return r.length===1?cE(e[0],r[0],t):void 0;if(s==="numeric"&&!i)return r.length===1?pE(e[0],r[0],t):void 0;if(s==="numeric"&&i&&r.length===1){let a=mE(e[0],r[0],t);if(a!==void 0)return a}}let o=await da(Ep(e[0],r,(s,a)=>{let u=a.evaluate({numericApproximation:i});return wE(s,u)??s.mul(u)},t.One),t._timeRemaining,n.signal);if(o!==Xo)return o?.evaluate({numericApproximation:i})??t.NaN}},Sum:{description:"`Sum(f, [a, b])` computes the sum of `f` from `a` to `b`; `Sum(L)` sums the elements of a collection `L`",keywords:["summation","sigma"],wikidata:"Q218005",complexity:1e3,broadcastable:!1,scoped:!0,lazy:!0,signature:"(any, tuple*) -> number",type:vE,canonical:([e,...n],{scope:t,engine:i})=>{if(n.length===0){let r=e?.canonical;if(r?.isCollection)return i._fn("Sum",[r])}return gE("Sum",e,n,t)},evaluate:([e,...n],{engine:t,numericApproximation:i})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Ko(e)?void 0:St(_A(e,t.Zero,(u,l)=>lh(u,l.evaluate({numericApproximation:i}),i)),t._timeRemaining)?.evaluate({numericApproximation:i})??t.NaN;let r=i,o=yp(e,n,t);if(o==="symbolic")return n.length===1?lE(e,n[0],t):void 0;if(o==="numeric"&&!r)return n.length===1?fE(e,n[0],t):void 0;if(o==="numeric"&&r&&n.length===1){let a=dE(e,n[0],t);if(a!==void 0)return a}let s=St(Ep(e,n,(a,u)=>lh(a,u.evaluate({numericApproximation:r}),r),t.Zero),t._timeRemaining);if(s!==Xo)return s?.evaluate({numericApproximation:r})??t.NaN},evaluateAsync:async([e,...n],{engine:t,signal:i,numericApproximation:r})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Ko(e)?void 0:(await da(_A(e,t.Zero,(u,l)=>lh(u,l.evaluate({numericApproximation:r}),r)),t._timeRemaining,i))?.evaluate({numericApproximation:r})??t.NaN;let o=r;{let a=yp(e,n,t);if(a==="symbolic")return n.length===1?lE(e,n[0],t):void 0;if(a==="numeric"&&!o)return n.length===1?fE(e,n[0],t):void 0;if(a==="numeric"&&o&&n.length===1){let u=dE(e,n[0],t);if(u!==void 0)return u}}let s=await da(Ep(e,n,(a,u)=>lh(a,u.evaluate({numericApproximation:o}),o),t.Zero),t._timeRemaining,i);if(s!==Xo)return s?.evaluate({numericApproximation:o})??t.NaN}},Interpret:{description:"Interpret a notational expression as its mathematical meaning. In v1: a continuation-bearing `Add`/`Multiply` (e.g. `1 + 2 + \\dots + n`) becomes a `Sum`/`Product`. Returns the argument unchanged when the (strict) inference gate does not pass",complexity:9e3,broadcastable:!1,lazy:!0,signature:"(any) -> any",evaluate:([e])=>{if(e)return Np(e)??e}}}];function SA(e,n,t){if(t>100)return;let i=e.One;for(let o=0;o<t;o++){let s=n.add(o);if(s.isSame(0))return e.ComplexInfinity;i=i.mul(s)}let r=1n;for(let o=2;o<t;o++)r*=BigInt(o);return e.number(r).div(i)}function wE(e,n){if(e.operator==="Error")return e;if(q(n))return e.engine.typeError("number",n.type)}function lh(e,n,t){let i=wE(e,n);if(i)return i;let r=e.add(n);return t?r:N(e)&&e.isExact&&N(n)&&n.isExact&&N(r)&&!r.isExact?e.engine.function("Add",[e,n]):r}function*_A(e,n,t){let i=n;for(let r of e.each())i=t(i,r),yield i;return i}function lV(e,n){let t=e.engine;if(N(e)){let i=e.numericValue;if(typeof i=="number")return t.number(Math.abs(i));if(i.im!==0){let r=i.re,o=i.im,s=r*r+o*o;if(Number.isInteger(r)&&Number.isInteger(o)&&Number.isSafeInteger(s))return t.function("Sqrt",[t.number(s)]).evaluate({numericApproximation:n})}return t.number(i.abs())}if(e.isNonNegative)return e;if(e.isNegative)return e.neg();if(e.unknowns.length===0){let i=e.N(),r=i.re,o=i.im;if(Number.isFinite(r)&&Number.isFinite(o)&&o!==0){let s=Pl(e);if(s){let[a,u]=s,l=t.function("Add",[t.function("Multiply",[a,a]),t.function("Multiply",[u,u])]),c=Pe(l).evaluate();if(N(c)&&c.im===0&&c.isNonNegative===!0){let f=r*r+o*o,p=c.re;if(Number.isFinite(p)&&Math.abs(p-f)<=1e-10*(1+Math.abs(f)))return t.function("Sqrt",[c]).evaluate({numericApproximation:n})}}}}}function Pl(e){let n=e.engine;if(N(e)){let t=e.json;return Array.isArray(t)&&t[0]==="Complex"?[n.box(t[1]),n.box(t[2])]:[e,n.Zero]}if(m(e)){let t=e.operator;if(t==="Add"){let i=[],r=[];for(let o of e.ops){let s=Pl(o);if(!s)return;i.push(s[0]),r.push(s[1])}return[n.function("Add",i),n.function("Add",r)]}if(t==="Negate"){let i=Pl(e.op1);return i?[i[0].neg(),i[1].neg()]:void 0}if(t==="Subtract"){let i=Pl(e.op1),r=Pl(e.op2);return!i||!r?void 0:[n.function("Subtract",[i[0],r[0]]),n.function("Subtract",[i[1],r[1]])]}if(t==="Multiply"){let i=n.One,r=n.Zero;for(let o of e.ops){let s=Pl(o);if(!s)return;let[a,u]=s,l=n.function("Subtract",[n.function("Multiply",[i,a]),n.function("Multiply",[r,u])]),c=n.function("Add",[n.function("Multiply",[i,u]),n.function("Multiply",[r,a])]);i=l,r=c}return[i,r]}if(t==="Complex")return[e.op1,e.op2]}return[e,n.Zero]}function TA(e,n){let t=e.engine,i=n==="Max"||n==="Supremum";if(m(e,"Interval")){let r=i?e.op2:e.op1;return!r.isNumber||!N(r)?[void 0,[e]]:[r,[]]}if(e.operator==="Range"){if(Yr(e))return[void 0,[e]];if(i){let r=ji(e),o=Jk(r);return[t.number(Math.max(r[0],o)),[]]}else return[t.number(ji(e)[0]),[]]}if(m(e,"Linspace"))return e.nops===1?e=i?e.op1:t.One:i?e=e.op2:e=e.op1,[e,[]];if(e.isCollection){if(e.isFiniteCollection!==!0||Ko(e))return[void 0,[e]];let r,o=[];for(let s of e.each()){let[a,u]=TA(s,n);if(a){if(a.isNaN)return[t.NaN,[]];a.im!==0?o.push(a):r?(i&&a.isGreater(r)||!i&&a.isLess(r))&&(r=a):r=a}o.push(...u)}return[r,o]}return!e.isNumber||!N(e)?[void 0,[e]]:[e,[]]}function IE(e,n,t,i){let r=e.engine;if(e.isNaN===!0||n.isNaN===!0)return r.NaN;if(N(e)&&e.im!==0||N(n)&&n.im!==0)return;let o=t?n.isGreater(e):n.isLess(e);if(o===void 0)return;let s=o?n:e;return i?s.N():s}function NA(e,n,t){if(e.length===0)return;let i=e[0];for(let r=1;r<e.length;r++){let o=IE(i,e[r],n,!1);if(o===void 0)return;i=o}return t?i.N():i}function ch(e,n,t){let i=t==="Max"||t==="Supremum";if(n=we(n),n.length===0)return i?e.NegativeInfinity:e.PositiveInfinity;let r,o=[];for(let s of n){let[a,u]=TA(s,t);if(a){if(a.isNaN)return e.NaN;a.im!==0?o.push(a):r?(i&&a.isGreater(r)||!i&&a.isLess(r))&&(r=a):r=a}o.push(...u)}return o.length>0?e.expr(r?[t,r,...o]:[t,...o]):r??(i?e.NegativeInfinity:e.PositiveInfinity)}function wA(e,n,t){let i=t==="LCM"?ma:Dn,r=t==="LCM"?$M:Y1;if(n.length===0)return t==="LCM"?e.One:e.Zero;if(n.some(a=>a.isCollection)){let a=!0,u=[...n];for(;a&&u.some(l=>l.isCollection);){let l=[];for(let c of u)if(c.isCollection){if(c.isFiniteCollection!==!0||Ko(c)){a=!1;break}for(let f of c.each())l.push(f)}else l.push(c);a&&(u=l)}if(a){if(u.length===0)return t==="LCM"?e.One:e.Zero;n=u}}if(n.length>0&&n.some(a=>N(a)&&!a.isExact)&&n.every(a=>N(a)&&Number.isFinite(a.re)&&!a.im)){let a=t==="LCM"?Ud:qc,u=Math.abs(n[0].re);for(let l=1;l<n.length;l++)u=a(u,n[l].re);return e.number(u)}let o=[];if(en(e)){let a=null;for(let u of n)if(a===null){let l=J1(u);l!==null&&l.isInteger()?a=l.abs():o.push(u)}else{let l=J1(u);l&&l.isInteger()?a=r(a,l):o.push(u)}return o.length===0?a===null?e.One:e.number(a):a===null?e._fn(t,o):e._fn(t,[e.number(a),...o])}let s=null;for(let a of n)s===null?a.isInteger?s=Math.abs(a.re):o.push(a):a.isInteger?s=i(s,a.re):o.push(a);return o.length===0?s===null?e.One:e.number(s):s===null?e._fn(t,o):e._fn(t,[e.number(s),...o])}var cV=new Set(["Negate","Add","Subtract","Multiply","Divide","Square","Exp","Power"]),fV=new Map([["Multiply",["Divide"]],["Divide",["Power"]],["Root",["Power"]]]),pV=8,MA=new WeakMap;function TE(e,n,t=pV){if(e.length<t)return;let i=MA.get(e);return(i===void 0||i.count!==e.length)&&(i={count:e.length},MA.set(e,i)),n?i.variations??=CA(e,!0):i.plain??=CA(e,!1)}function CA(e,n){let t=new Map,i=[],r=(o,s)=>{let a=t.get(o);a?a.push(s):t.set(o,[s])};for(let o=0;o<e.length;o++){let s=e[o],a={rule:s,ordinal:o};if(s.operators!==void 0&&s.operators.length>0){for(let f of s.operators)r(f,a);continue}let u=s.match;if(u===void 0){i.push(a);continue}if(!m(u)){i.push(a);continue}let l=u.operator;if(l.startsWith("_")){i.push(a);continue}if((s.useVariations??n)&&cV.has(l)){i.push(a);continue}r(l,a)}return{byHead:t,alwaysTry:i,count:e.length}}function dV(e,n){let t=0,i=e.length;for(;t<i;){let r=t+i>>1;e[r].ordinal>n?i=r:t=r+1}return t}function*fh(e,n,t){let i=[];e.alwaysTry.length>0&&i.push(e.alwaysTry);let r=n.operator,o=e.byHead.get(r);o!==void 0&&i.push(o);let s=fV.get(r);if(s!==void 0)for(let l of s){let c=e.byHead.get(l);c!==void 0&&i.push(c)}if(N(n)){let l=e.byHead.get("Divide");l!==void 0&&i.push(l)}let a=i.map(l=>dV(l,t)),u=-1;for(;;){let l=-1,c=1/0;for(let p=0;p<i.length;p++)if(a[p]<i[p].length){let d=i[p][a[p]].ordinal;d<c&&(c=d,l=p)}if(l<0)return;let f=i[l][a[l]++];f.ordinal!==u&&(u=f.ordinal,yield f)}}function kA(e){return e.match===void 0&&typeof e.replace=="function"&&e.condition===void 0&&e.useVariations!==!0&&e.operators!==void 0&&e.operators.length===1}var mV={};function gV(e,n){let t=n.map(o=>o.replace),i=t.length;return{_tag:"boxed-rule",match:void 0,replace:o=>{let s=o,a;for(let u=0;u<i;u++){let l=t[u](s,mV);if(l!=null&&"because"in l){let c=l;s=c.value,a=c}}return a},condition:void 0,operators:[e],id:`hot-head-dispatch:${e}`}}function AA(e){let n=new Map;for(let o of e){if(!kA(o))continue;let s=o.operators[0],a=n.get(s);a?a.push(o):n.set(s,[o])}let t=new Map;for(let[o,s]of n)s.length>=2&&t.set(o,gV(o,s));if(t.size===0)return e;let i=new Set,r=[];for(let o of e){if(kA(o)){let s=o.operators[0],a=t.get(s);if(a!==void 0){i.has(s)||(i.add(s),r.push(a));continue}}r.push(o)}return r}var RA=new WeakSet;var FA={boolean:e=>e.type.matches("boolean"),string:e=>q(e),number:e=>N(e),symbol:e=>w(e),expression:e=>!0,numeric:e=>{let[n,t]=e.toNumericValue();return t.isSame(1)},integer:e=>e.isInteger,rational:e=>e.isRational,irrational:e=>e.isReal===!0&&e.isRational===!1,real:e=>e.isReal,notreal:e=>e.isReal===!1,complex:e=>e.type.matches("complex"),imaginary:e=>e.type.matches("imaginary"),positive:e=>e.isPositive,negative:e=>e.isNegative,nonnegative:e=>e.isNonNegative,nonpositive:e=>e.isNonPositive,even:e=>e.isEven,odd:e=>e.isOdd,prime:e=>fp(e)===!0,composite:e=>e.isInteger===!0&&e.isPositive===!0&&e.isEqual(1)===!1&&fp(e)===!1,notzero:e=>e.isEqual(0)===!1,notone:e=>e.isEqual(1)===!1,finite:e=>e.isFinite,infinite:e=>e.isFinite===!1,constant:e=>e.valueDefinition?.isConstant??!1,variable:e=>!(e.valueDefinition?.isConstant??!0),function:e=>e.operatorDefinition!==void 0,relation:e=>mt(e.operator),equation:e=>e.operator==="Equal",inequality:e=>rr(e.operator),collection:e=>e.isCollection,list:e=>e.operator==="List",set:e=>e.operator==="Set",tuple:e=>e.operator==="Tuple"||e.operator==="Single"||e.operator==="Pair"||e.operator==="Triple",single:e=>e.operator==="Single",pair:e=>e.operator==="Pair",triple:e=>e.operator==="Triple",scalar:e=>e.rank===0,tensor:e=>e.rank>0,vector:e=>e.rank===1,matrix:e=>e.rank===2,unit:e=>e.operator==="Unit",dimension:e=>e.operator==="Dimension",angle:e=>e.operator==="Angle",polynomial:e=>e.unknowns.length===1};function BA(e,n){for(let t of n)if(FA[t](e)!==!0)return!1;return!0}function $A(e,n){let t=e._isVerifying;e._isVerifying=!0;try{return w(n.evaluate(),"True")}finally{e._isVerifying=t}}function hV(e){let n=/\\[a-zA-Z]+|[{}]|[\d]+|[+\-*/^_=()><,.;]|[a-zA-Z]/g,t=e.match(n);return t?t.filter(i=>!/^[ \f\n\r\t\v\xA0\u2028\u2029]+$/.test(i)):[]}function bV(e){let n=e.peek,t=null;if(n==="\\mathrm")e.nextToken(),t=e.parseStringGroup();else if(/^[a-z]$/.test(n))for(t=e.nextToken();/^[a-z]$/.test(e.peek);)t+=e.nextToken();else{let i={">0":"positive","\\gt0":"positive","<0":"negative","\\lt0":"negative",">=0":"nonnegative","\\geq0":"nonnegative","<=0":"nonpositive","\\leq0":"nonpositive","!=0":"notzero","\\neq0":"notzero","\\neq1":"notone","!=1":"notone","\\in\\R":"real","\\in\\mathbb{R}":"real","\\in\\C":"complex","\\in\\mathbb{C}":"complex","\\in\\Q":"rational","\\in\\mathbb{Q}":"rational","\\in\\Z^+":"integer,positive","\\in\\Z^-":"integer,negative","\\in\\Z^*":"integer,notzero","\\in\\R^+":"positive","\\in\\R^-":"negative","\\in\\R^*":"real,notzero","\\in\\Z":"integer","\\in\\mathbb{Z}":"integer","\\in\\N":"integer,nonnegative","\\in\\mathbb{N}":"integer,nonnegative","\\in\\N^*":"integer,positive","\\in\\N_0":"integer,nonnegative","\\in\\R\\backslash\\Q":"irrational"};for(let r in i)if(e.matchAll(hV(r))){t=i[r];break}}if(!t)return null;for(let i of t.split(","))if(!Object.keys(FA).includes(i))throw new Error(`Unexpected condition "${i}" in a rule`);return t}function PA(e){let n=[];do{let t=bV(e);if(!t)break;n.push(t)}while(e.match(","));return n.join(",")}function ME(e){let n=null;if(e.match(":"))n=PA(e);else if(e.matchAll(["_","<{>"])&&(n=PA(e),!e.match("<}>")))return null;return n}function yV(e){return w(e,"e")?e.engine.symbol("ExponentialE",{canonical:!1}):w(e,"i")?e.engine.I:e}function ph(e){return e.map(yV,{canonical:!1})}function xV(e){if(m(e,"InvisibleOperator")&&w(e.ops[0],"_")){let n=e.ops.slice(1);if(n.length>0&&n.every(t=>w(t)))return e.engine.symbol("_"+n.map(t=>t.symbol).join(""))}return m(e,"Subscript")&&w(e.op1,"_")&&w(e.op2)?e.engine.symbol("__"+e.op2.symbol):e}function DA(e,n,t){if(n===void 0||typeof n=="function")return;if(typeof n=="string"){let r=e.parse(n,{form:t?.canonical?"canonical":"raw"})??e.expr("Nothing");return r=ph(r),r=r.map(xV,{canonical:!1}),t?.autoWildcard&&(r=r.map(o=>w(o)&&o.symbol.length===1?e.symbol("_"+o.symbol):o,{canonical:!1})),r}let i=t?.canonical??(n instanceof Je?n.isCanonical:!1);return e.expr(n,{form:i?"canonical":"raw"})}function EV(e,n,t){let i=p=>({kind:"symbol",latexTrigger:p,parse:(d,g)=>{r[p]||(r[p]=`_${p}`);let h=ME(d);return h!==null&&(o[p]?o[p]+=","+h:o[p]=h),r[p]}}),r={},o={},s=[...Aa,{kind:"prefix",precedence:100,latexTrigger:"...",parse:(p,d)=>{let g=p.nextToken();if(!"abcfghjklmnopqrstuvwxyz".includes(g))return null;let h="__";if(p.match("?")&&(h="___"),r[g]&&r[g]!==`${h}${g}`)throw new Error(`Duplicate wildcard "${g}"`);r[g]||(r[g]=`${h}${g}`);let b=ME(p);return b===null?`${h}${g}`:(o[g]?o[g]+=","+b:o[g]=b,`${h}${g}`)}},..."abcfghjklmnopqrstuvwxyz".split("").map(i),{kind:"infix",precedence:100,latexTrigger:"->",parse:(p,d,g)=>{let h=p.parseExpression({...g,minPrec:20});if(h===null)return null;let b=null;if(p.match(";")){let E=!1,v=p.index;do{p.skipSpace();let _=p.nextToken();if(r[_]){let I=ME(p);if(I===null||!I){E=!0,p.index=v;break}o[_]?o[_]+=","+I:o[_]=I}}while(!E&&!p.atEnd);b=p.parseExpression(g)}let y=[];for(let E in o){let v=o[E].split(",");v.length!==0&&(v.length===1?y.push(["Condition",r[E],v[0]]):y.push(["Condition",r[E],["And",...v]]))}let x;return b&&y.length>0?x=["And",b,...y]:b?x=b:y.length===1?x=y[0]:y.length>1&&(x=["And",...y]),x?["Rule",d,h,x]:["Rule",d,h]}}],a=t?.canonical??!1,u=e._requireLatexSyntax().constructor,l=new u({dictionary:s}),c=e.contextStack[0]?.lexicalScope;c&&e.pushScope({parent:c,bindings:new Map});let f;try{if(f=e.expr(l.parse(n)??"Nothing"),!f.isValid||f.operator!=="Rule")throw new Error(`Invalid rule "${n}"
|
|
49
49
|
| ${JA(f).toString()}
|
|
50
50
|
| A rule should be of the form:
|
|
51
51
|
| <match> -> <replace>; <condition>`);if(!m(f))throw new Error(`Invalid rule "${n}"`);let[p,d,g]=f.ops,h=ph(p),b=ph(d),y=g!==void 0?ph(g):void 0;if(a&&(h=h.canonical,b=b.canonical),!LA(b,h))throw new Error(`Invalid rule "${n}"
|
|
@@ -86,10 +86,10 @@ Error in value definition of "${i}"`,"",JSON.stringify(r,void 0,4),"",o instance
|
|
|
86
86
|
Error in definition of "${i}"`,"",JSON.stringify(r,void 0,4),"",o instanceof Error?o.message:String(o)].join(`
|
|
87
87
|
| `)+`
|
|
88
88
|
`)}}function Ab(e){return typeof e=="number"?e===0?1:Number.isInteger(e)?Math.floor(Math.log2(Math.abs(e))/Math.log2(10))+(e>0?1:2):2:e.isZero?1:e.im!==0?Ab(e.re)+Ab(e.im)+1:Ab(e.re)}function Mi(e){let n=(()=>{if(!m(e,"Multiply")||e.ops.length!==2)return null;let o=(l,c)=>{if(!m(c,"Power")||!w(c.op1,"ExponentialE")||!m(l,"Power"))return null;let f=l.op2;if(!m(f,"Divide")||f.op1?.isSame(1)!==!0)return null;let p=f.op2;return!m(p,"Ln")||p.op1?.isSame(10)!==!0?null:{xBase:l.op1,eExp:c.op2}},[s,a]=e.ops,u=o(s,a)??o(a,s);return u?12+Mi(u.xBase)+Mi(u.eExp):null})();if(n!==null)return n;if(w(e))return 1;if(N(e))return Ab(e.numericValue);let t=e.operator,i=2;if(["Add"].includes(t))i=3;else if(t==="Subtract")i=4;else if(t==="Negate"){let o=m(e)?e:void 0;if(o?.op1?.operator==="Power"){let s=m(o.op1)?o.op1:void 0;if(s)return 3+Mi(s.ops[1])}i=4}else if(t==="Sqrt"){let s=(m(e)?e:void 0)?.ops[0];if(m(s,"Multiply")){for(let a of s.ops)if(m(a,"Power")&&a.op2?.isEven===!0)return 5+Mi(s)+6}if(m(s,"Power")&&s.op2?.isEven===!0)return 5+Mi(s)+6;if(m(s,"Power")&&s.op2?.isOdd===!0&&s.op2?.isInteger===!0){let a=s.op2,u=ze(a);if(typeof u=="number"&&u>1)return 5+Mi(s)+10}i=5}else if(["Square","Abs"].includes(t))i=5;else if(t==="Power"){let o=m(e)?e:void 0;if(o){let s=o.ops[0],a=o.ops[1],u=Mi(a);return s.operator==="Negate"?u+4:m(s,"Multiply")?s.ops.some(c=>N(c)&&c.isNegative===!0)&&a.isRational===!0&&!a.isInteger?u+Mi(s)+15:u+Mi(s):u}}else if(t==="Root")i=5;else if(["Multiply"].includes(t)){let s=(m(e)?e:void 0)?.ops??[];if(s.length===2&&N(s[0])){let a=s[0].numericValue,u=!1;if(typeof a=="number")u=Number.isInteger(a)&&Math.abs(a)<=10;else if(a){let l=a.type;(l==="finite_integer"&&Math.abs(a.re)<=10||l==="finite_rational")&&(u=!0)}if(u){let l=s[1].operator;return["Ln","Log","Lb"].includes(l)?2+Mi(s[1]):3+Mi(s[1])}}i=7}else["Divide"].includes(t)?i=8:["Ln","Exp","Log","Lb"].includes(t)?i=9:["Cos","Sin","Tan"].includes(t)?i=10:i=11;let r=m(e)?e:void 0;return i+(r?.ops.reduce((o,s)=>o+Mi(s),0)??0)}var h4=Mi;function X2(e,n,t){return e.generation===n&&e.value!==null||(e.generation=n,e.value=t()),e.value}var zZ=[5,5],b4=0,Sn=class extends Je{_kind="function";_operator;_ops;_def;_localScope;_isPure;_isStructural;_hash;_value={value:null,generation:-1};_valueN={value:null,generation:-1};_sgn={value:null,generation:-1};_type={value:null,generation:-1};constructor(n,t,i,r){super(n,r?.metadata),this._operator=t,this._ops=i,this._localScope=r?.scope,this._isStructural=r?.structural??!1,(r?.canonical||this._isStructural)&&this.bind()}get hash(){if(this._hash!==void 0)return this._hash;let n=0;for(let t of this._ops)n=n<<1^t.hash|0;return n=n^Fi(this._operator)|0,this._hash=n,n}infer(n,t){let i=this.operatorDefinition;if(!i||!i.inferredSignature)return!1;if(i.signature.is("function"))i.signature=new Z({kind:"signature",result:n},this.engine._typeResolver);else if(jd(i.signature.type)){let r=i.signature.type;if(t!=="narrow"&&$(r.result,n))return!0;i.signature=new Z({kind:"signature",args:r.args,optArgs:r.optArgs,variadicArg:r.variadicArg,variadicMin:r.variadicMin,result:t==="narrow"?fs(r.result,n):Te(r.result,n)},this.engine._typeResolver)}return this.engine._generation+=1,this.engine._mutationGeneration+=1,!0}bind(){this._def=Qd(this._operator,this._localScope??this.engine.context.lexicalScope)}reset(){}get value(){}get isCanonical(){return this._def!==void 0&&this._def!==null&&!this._isStructural}get isPure(){if(this._isPure!==void 0)return this._isPure;let n=this.operatorDefinition?.pure??!1;return n&&(n=this._ops.every(t=>t.isPure)),this._isPure=n,n}get isConstant(){return this.isPure&&this._ops.every(n=>n.isConstant)}get json(){let n=this.structural,t=m(n)?n.ops:this._ops;return[this._operator,...t.map(i=>i.json)]}get operator(){return this._operator}get ops(){return this._ops}get nops(){return this._ops.length}get op1(){return this._ops[0]??this.engine.Nothing}get op2(){return this._ops[1]??this.engine.Nothing}get op3(){return this._ops[2]??this.engine.Nothing}get isScoped(){return this._localScope!==void 0}get localScope(){return this._localScope}get isValid(){return this._operator==="Error"?!1:this._ops.every(n=>n?.isValid)}get canonical(){return this.isCanonical||!this.isValid?this:this.engine.function(this._operator,this._ops)}get structural(){if(this.isStructural)return this;let n=this.operatorDefinition;if((n?.associative||n?.commutative)&&!this.ops.some(t=>Mn(t))){let t=this.ops.map(r=>r.structural),i=[];if(!n.associative)i=t;else for(let r of t)m(r,this.operator)?i.push(...r.ops):i.push(r);return this.engine.function(this._operator,this.isValid?qf(this._operator,i):i,{form:"structural",metadata:{latex:this.verbatimLatex,sourceOffsets:this.sourceOffsets}})}return this.engine.function(this._operator,this.ops.map(t=>t.structural),{form:"structural",metadata:{latex:this.verbatimLatex,sourceOffsets:this.sourceOffsets}})}get isStructural(){return this._isStructural}toNumericValue(){this.isCanonical||this.isStructural;let n=this.engine;if(this.operator==="Complex")return[n._numericValue({re:this.op1.re,im:this.op2.re}),n.One];let t=this;if(t.operator==="Add"&&(t=Wa(t),N(t))){if(typeof t.numericValue=="number"){if(Number.isInteger(t.numericValue))return[n._numericValue(t.numericValue),n.One]}else if(t.numericValue.isExact)return[t.numericValue,n.One]}if(m(t,"Negate")){let[i,r]=t.op1.toNumericValue();return[i.neg(),r]}if(m(t,"Multiply")){let i=[],r=n._numericValue(1);for(let o of t.ops){let[s,a]=o.toNumericValue();s.isOne||(r=r.mul(s)),a.isSame(1)||i.push(a)}return i.length===0?[r,n.One]:i.length===1?[r,i[0]]:[r,at(n,i)]}if(m(t,"Divide")){let[i,r]=t.op1.toNumericValue(),[o,s]=t.op2.toNumericValue(),a=i.div(o);return s.isSame(1)?[a,r]:[a,n.function("Divide",[r,s])]}if(m(t,"Power")){if(!N(t.op2))return[n._numericValue(1),this];let[i,r]=t.op1.toNumericValue();if(i.isOne)return[i,this];let o=Q(t.op2);return o!==null?[i.pow(o),n.function("Power",[r,t.op2])]:[n._numericValue(1),this]}if(m(t,"Sqrt")){let[i,r]=t.op1.toNumericValue();return r.isSame(1)||r.isSame(0)?i.isOne||i.isZero?[i,r]:[i.sqrt(),r]:i.sgn()===-1?[i.neg().sqrt(),n.function("Sqrt",[r.neg()])]:[i.sqrt(),n.function("Sqrt",[r])]}if(m(t,"Root")){let i=t.op2.re;if(isNaN(i)||t.op2.im!==0)return[n._numericValue(1),this];let[r,o]=t.op1.toNumericValue();if(i%2===0&&r.sgn()===-1)return[n._numericValue(1),this];let s=r.root(i);return!s.isExact&&(!o.isSame(1)||r.isExact)?[n._numericValue(1),this]:[s,n.function("Root",[o,t.op2])]}if(m(t,"Abs")){let[i,r]=t.op1.toNumericValue();return[i.abs(),n.function("Abs",[r])]}return t.operator,t.operator==="Exp"||t.operator==="Log"||t.operator==="Ln"?[n._numericValue(1),this]:[n._numericValue(1),t]}subs(n,t){t??={canonical:void 0},t.canonical===void 0&&(t={canonical:this.isCanonical||this.isStructural});let i=this._ops.map(o=>t.canonical===!0&&!o.isCanonical?o.subs(n,{canonical:!1}):o.subs(n,t)),r=t.canonical===!0?"canonical":t.canonical===!1?"raw":t.canonical;return i.every(o=>o.isValid)?this.engine.function(this._operator,i,{form:r}):this.engine.function(this._operator,i,{form:"raw"})}replace(n,t){return es(this,n,t).at(-1)?.value??null}match(n,t){return Bl(this,n,t)}has(n){if(typeof n=="string"){if(this._operator===n)return!0}else if(n.includes(this._operator))return!0;return this._ops.some(t=>t.has(n))}get sgn(){let n=this.isPure&&this._ops.every(t=>t.isConstant)?void 0:this.engine._generation;return X2(this._sgn,n,()=>{if(!(!this.isValid||this.isNumber!==!0))return YR(this)})}get isNaN(){if(!this.isNumber)return!1}get isInfinity(){if(!this.isNumber)return!1}get isFinite(){if(this.isNumber!==!0||this.isNaN===!0||this.isInfinity===!0)return!1;let n=t=>t.isPositive===!0||t.isNegative===!0;switch(this.operator){case"Abs":return this.op1.isFinite;case"Sqrt":return this.op1.isFinite;case"Root":{let t=this.op1.isFinite,i=this.op2.isFinite;if(t===!1||i===!1)return;if(t===!0&&i===!0&&n(this.op2))return!0;break}case"Power":{let t=this.op1.isFinite,i=this.op2.isFinite;if(t===!0&&i===!0&&(n(this.op1)||this.op2.isPositive===!0))return!0;break}case"Divide":{let t=this.op1.isFinite,i=this.op2.isFinite;if(t===!0&&i===!0&&n(this.op2))return!0;break}}if(!(this.isNaN===void 0||this.isInfinity===void 0))return!0}get _isOne(){if(this.isNonPositive===!0||this.isReal===!1)return!1}get _isNegativeOne(){if(this.isNonNegative===!0||this.isReal===!1)return!1}get isPositive(){return $l(this.sgn)}get isNonNegative(){return ql(this.sgn)}get isNegative(){return Vl(this.sgn)}get isNonPositive(){return Jl(this.sgn)}get numerator(){return this.numeratorDenominator[0]}get denominator(){return this.numeratorDenominator[1]}get numeratorDenominator(){if(!(this.isCanonical||this.isStructural))return[this,this.engine.One];if(this.isNumber!==!0)return[this.engine.Nothing,this.engine.Nothing];let n=this.operator;if(n==="Divide")return[this.op1,this.op2];if(n==="Negate"){let[t,i]=this.op1.numeratorDenominator;return[t.neg(),i]}if(n==="Power"){let[t,i]=this.op1.numeratorDenominator;return[t.pow(this.op2),i.pow(this.op2)]}if(n==="Root"){let[t,i]=this.op1.numeratorDenominator;return[t.root(this.op2),i.root(this.op2)]}if(n==="Sqrt"){let[t,i]=this.op1.numeratorDenominator;return[t.sqrt(),i.sqrt()]}if(n==="Abs"){let[t,i]=this.op1.numeratorDenominator;return[t.abs(),i.abs()]}return n==="Multiply"?new oi(this.engine,this.ops).asNumeratorDenominator():[this,this.engine.One]}factors(){let n=this.operator;if(n==="Multiply"){let t=[];for(let i of this.ops)t.push(...i.factors());return t}return n==="Negate"?[this.engine.number(-1),...this.op1.factors()]:[this]}toRational(){let n=this.operator;if(n==="Divide"||n==="Rational"){let t=this.op1.re,i=this.op2.re;if(Number.isInteger(t)&&Number.isInteger(i)&&i!==0){let r=Dn(Math.abs(t),Math.abs(i)),o=i<0?-1:1;return[o*t/r,o*i/r]}return null}if(n==="Negate"){let t=this.op1.toRational();return t?[-t[0],t[1]]:null}return null}neg(){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");return $a(this)}inv(){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");if(this._isOne)return this;if(this._isNegativeOne)return this;if(this.operator==="Sqrt"&&this.op1.isNonNegative===!0)return this.op1.inv().sqrt();if(this.operator==="Divide")return this.op2.div(this.op1);if(this.operator==="Power"){let n=this.op2.neg();return n.operator!=="Negate"?this.op1.pow(n):this.engine.function("Power",[this.op1,n])}if(this.operator==="Root"){let n=this.op2.neg();return n.operator!=="Negate"?this.op1.root(n):this.engine.function("Root",[this.op1,n])}return this.operator==="Exp"?this.engine.E.pow(this.op1.neg()):this.operator==="Rational"?this.op2.div(this.op1):this.operator==="Negate"?this.op1.inv().neg():this.engine._fn("Divide",[this.engine.One,this])}abs(){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");return this.operator==="Abs"||this.operator==="Negate"?this:this.isNonNegative?this:this.isNonPositive?this.neg():this.engine._fn("Abs",[this])}add(n){if(n===0)return this;if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");return te(this,this.engine.expr(n))}mul(n){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");if(n===0)return this.engine.Zero;if(n===1)return this;if(n===-1)return this.neg();if(n instanceof je){if(n.isZero)return this.engine.Zero;if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return he(this,this.engine.expr(n))}div(n){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");return ll(this,n)}pow(n){return sn(this,n,{numericApproximation:!1})}root(n){if(!(this.isCanonical||this.isStructural)||typeof n!="number"&&!(n.isCanonical||n.isStructural))throw new Error("Not canonical");let t=typeof n=="number"?n:n.im===0?n.re:void 0;if(t===0)return this.engine.NaN;if(t===1)return this;if(t===-1)return this.inv();if(t===2)return this.engine.function("Sqrt",[this]);if(this.operator==="Power"&&t!==void 0){let[i,r]=this.ops;return i.pow(r.div(t))}if(this.operator==="Divide"){let[i,r]=this.ops;return i.root(n).div(r.root(n))}if(this.operator==="Negate"&&t!==void 0)return t%2===0?this.op1.root(n):this.op1.root(n).neg();if(this.operator==="Sqrt"){if(t!==void 0)return this.op1.root(t*2);if(typeof n!="number")return this.op1.root(n.mul(2))}if(this.operator==="Root"){let[i,r]=this.ops;return i.root(r.mul(n))}if(this.operator==="Multiply"){let i=this.ops.map(r=>r.root(n));return he(...i)}if(this.isNumberLiteral){let i=this.numericValue;if(typeof i=="number"){if(i<0)return this.engine.NaN;if(i===0)return this.engine.Zero;if(i===1)return this.engine.One;if(t!==void 0){let r=this.engine.number(Math.pow(i,1/t));if(!r.isFinite||r.isInteger)return r}}else{if(i.isOne)return this.engine.One;if(i.isZero)return this.engine.Zero;if(t!==void 0){let r=i.root(t);if(r.isExact)return this.engine.number(r)}}}return t!==void 0&&t<0&&Number.isInteger(t)?this.engine._fn("Divide",[this.engine.One,this.root(-t)]):this.engine._fn("Root",[this,this.engine.expr(n)])}sqrt(){return this.root(2)}ln(n){let t=n?this.engine.expr(n):void 0;if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");if(this.isSame(0))return this.engine.NegativeInfinity;if(this.operator==="Exp")return t?this.op1.div(t.ln()):this.op1;if(t&&this.isSame(t))return this.engine.One;if(this.isSame(this.engine.E))return t?this.engine.One.div(t.ln()):this.engine.One;if(this.operator==="Power"){let[i,r]=this.ops;if(i.isSame(this.engine.E))return t?r.div(t.ln()):r;if(i.isNonNegative===!0)return r.mul(i.ln(t));if(r.isEven===!0&&Rn(i))return r.mul(this.engine._fn("Abs",[i]).ln(t));if(Rn(i)&&io(this.engine,"Ln",i)!==!0)return r.mul(i.ln(t))}if(this.operator==="Root"){let[i,r]=this.ops;if(i.isNonNegative===!0||Rn(i)&&io(this.engine,"Ln",i)!==!0)return i.ln(t).div(r)}if(this.operator==="Sqrt")return this.op1.ln(t).div(2);if(this.operator==="Divide"){let i=this.op1,r=this.op2;if((i.isNonNegative===!0||Rn(i)&&io(this.engine,"Ln",i)!==!0)&&(r.isNonNegative===!0||Rn(r)&&io(this.engine,"Ln",r)!==!0))return i.ln(t).sub(r.ln(t))}return t!==void 0?t.re===10?this.engine._fn("Log",[this]):this.engine._fn("Log",[this,t]):this.engine._fn("Ln",[this])}get complexity(){if(this.isCanonical||this.isStructural)return this.operatorDefinition?.complexity??1e5}get baseDefinition(){if(this._def)return fe(this._def)?this._def.operator:this._def.value}get operatorDefinition(){if(this._def)return fe(this._def)?this._def.operator:void 0}get valueDefinition(){if(this._def)return ie(this._def)?this._def.value:void 0}get isNumber(){if(!this.type.isUnknown)return $(this.type.type,"number")}get isInteger(){if(!this.type.isUnknown)return $(this.type.type,"integer")}get isRational(){if(!this.type.isUnknown)return $(this.type.type,"rational")}get isReal(){if(!this.type.isUnknown)return $(this.type.type,"real")}get isFunctionExpression(){return!0}get type(){let n=this.isPure&&this._ops.every(t=>t.isConstant)?void 0:this.engine._generation;return X2(this._type,n,()=>new Z(ZZ(this),this.engine._typeResolver))??Z.unknown}get shape(){let n=this.type.type;return typeof n=="object"&&n.kind==="list"&&n.dimensions?n.dimensions:[]}get rank(){return this.shape.length}simplify(n){return y4(this.engine,()=>Qr(this,n).at(-1)?.value??this)()}explain(n,t){return Fl(this,n,t)}evaluate(n){return y4(this.engine,this._computeValue(n))()}evaluateAsync(n){return HZ(this.engine,this._computeValueAsync(n))()}N(){return this.evaluate({numericApproximation:!0})}solve(n){let t=La(n??this.unknowns);if(this.operator==="List"||this.operator==="And"){let r=Sh(this.engine,this.ops,t);if(r!==null)return r}if(this.operator==="Or")return JR(this.ops,t);if(t.length!==1)return null;if(this.operator==="Congruent"){let r=BR(this.engine,this,t[0]);if(r!==void 0)return ts(this.engine,r,t[0])}let i=rn(this,t[0]);return i===null?null:ts(this.engine,i,t[0])}get isCollection(){if(!this.isValid)return!1;let n=this.baseDefinition?.collection;return!n||n.count!==void 0&&n.iterator,n!==void 0}get isIndexedCollection(){return!this.isValid||!this.baseDefinition?.collection?.at?!1:this.type.matches("indexed_collection")}get isLazyCollection(){if(!this.isValid)return!1;let n=this.baseDefinition?.collection;return n?n?.isLazy?.(this)??!1:!1}contains(n){return this.baseDefinition?.collection?.contains?.(this,n)}get count(){return this.operatorDefinition?.collection?.count?.(this)}get isEmptyCollection(){if(this.isCollection)return this.operatorDefinition?.collection?.isEmpty?.(this)}get isFiniteCollection(){if(this.isCollection)return this.operatorDefinition?.collection?.isFinite?.(this)}each(){let n=this.operatorDefinition?.collection?.iterator?.(this);if(!n){let i=this.evaluate();if(i!==this&&(n=i.operatorDefinition?.collection?.iterator?.(i)),!n)return(function*(){})()}let t=this.engine;return(function*(){let i=n.next(),r=0;for(;!i.done;)(++r&255)===0&&z(t._deadline),yield i.value,i=n.next()})()}at(n){let t=this.operatorDefinition?.collection?.at;if(t){if(n<0){if(this.isFiniteCollection!==!0)return;let i=this.count;if(i===void 0||!Number.isFinite(i))return;let r=i+1+n;return r<1?void 0:t(this,r)}return t(this,n)}}get(n){if(typeof n=="string")return this.operatorDefinition?.collection?.at?.(this,n);if(q(n))return this.operatorDefinition?.collection?.at?.(this,n.string)}indexWhere(n){if(this.operatorDefinition?.collection?.indexWhere)return this.operatorDefinition.collection.indexWhere(this,n);if(!this.isIndexedCollection||!this.isFiniteCollection)return;let t=1;for(let i of this.each()){if(n(i))return t;t+=1}}subsetOf(n,t){return this.operatorDefinition?.collection?.subsetOf?.(this,n,t)??!1}_computeValue(n){return()=>{if((++b4&1023)===0&&z(this.engine._deadline),!this.isValid||!this._def)return this;let t=n?.numericApproximation??!1,i=n?.materialization??!1;if(ie(this._def))return x4(this,this._def.value,n);let r=this._def.operator,o=this.ops.some(d=>W(d)),s=(this.operator==="Add"||this.operator==="Multiply")&&this.ops.some(d=>m(d)&&!Re(d));if(r.broadcastable&&!s&&this.ops.some(d=>Re(d)&&!Ye(d))&&!fd(this.operator,o,this.ops)){let d=ya(this.engine,this.operator,this._ops,pt,t);if(d)return d;let g=ms(this._ops);if(!g)return this.engine.Nothing;let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluate(n))}return h.length===0?this.engine.Nothing:this.engine._fn("List",h)}if(r instanceof yi&&r._isLambda&&this.ops.some(d=>Re(d)&&!Ye(d))&&cu(r)){let d=ya(this.engine,this.operator,this._ops,pt,t);if(d)return d;let g=ms(this._ops);if(g){let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluate(n))}return this.engine._fn("List",h)}}if(i!==!1&&!r.evaluate&&this.isLazyCollection)return WZ(this,r,n);if(t&&!r.evaluate&&this.isLazyCollection){let d=Ey(this.engine,this);if(d)return d}let a=gh(this,d=>d.evaluate(n)),u=r instanceof yi&&r._isLambda&&cu(r),l=d=>by(d)||r.lazy!==!0&&er(d);if((u||r.broadcastable&&this.operator!=="Add"&&this.operator!=="Multiply")&&!fd(this.operator,!1,a)&&a.some(l)){let d=ya(this.engine,this.operator,a,pt,t);if(d)return d;let g=ms(a);if(g){let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluate(n))}if(u)return this.engine._fn("List",h);if(h.length>0)return this.engine._fn("List",h)}}if(r.broadcastable&&!GZ.has(this.operator)&&a.some(d=>m(d,"When")||m(d,"Which"))){let d=UZ(this.engine,this.operator,a,r.lazy===!0,n);if(d)return d}let c=this._localScope!==void 0;c&&this.engine._pushEvalContext(this._localScope);let f;try{f=r.evaluate?.(a,{numericApproximation:t,engine:this.engine,materialization:i})}finally{c&&this.engine._popEvalContext()}let p=f??(c&&r.evaluate===void 0&&this.isCanonical&&a.every((d,g)=>d===this._ops[g])?this:this.engine.function(this._operator,a));return t?qv(this.engine,this._operator,a,p):p}}_computeValueAsync(n){return async()=>{if((++b4&1023)===0&&z(this.engine._deadline),!this.isValid||!this._def)return this;let t=n?.numericApproximation??!1;if(ie(this._def))return x4(this,this._def.value,n);let i=this._def.operator,r=this.ops.some(d=>W(d)),o=(this.operator==="Add"||this.operator==="Multiply")&&this.ops.some(d=>m(d)&&!Re(d));if(i?.broadcastable&&!o&&this.ops.some(d=>Re(d)&&!Ye(d))&&!fd(this.operator,r,this.ops)){let d=ya(this.engine,this.operator,this._ops,pt,t);if(d)return d;let g=ms(this._ops);if(!g)return this.engine.Nothing;let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluateAsync(n))}return h.length===0?this.engine.Nothing:Promise.all(h).then(b=>this.engine._fn("List",b))}if(i instanceof yi&&i._isLambda&&this.ops.some(d=>Re(d)&&!Ye(d))&&cu(i)){let d=ya(this.engine,this.operator,this._ops,pt,t);if(d)return d;let g=ms(this._ops);if(g){let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluateAsync(n))}return Promise.all(h).then(b=>this.engine._fn("List",b))}}if(t&&!i.evaluate&&this.isLazyCollection){let d=Ey(this.engine,this);if(d)return d}let s=await zA(this,async d=>await d.evaluateAsync(n)),a=i instanceof yi&&i._isLambda&&cu(i),u=d=>by(d)||i.lazy!==!0&&er(d),l=a||i.evaluate!==void 0;if((a||i.broadcastable&&this.operator!=="Add"&&this.operator!=="Multiply")&&l&&!fd(this.operator,!1,s)&&s.some(u)){let d=ya(this.engine,this.operator,s,pt,t);if(d)return d;let g=ms(s);if(g){let h=[];for(;;){let{done:b,value:y}=g.next();if(b)break;h.push(this.engine._fn(this.operator,y).evaluateAsync(n))}if(a)return Promise.all(h).then(b=>this.engine._fn("List",b));if(h.length>0)return Promise.all(h).then(b=>this.engine._fn("List",b))}}let c=this._localScope!==void 0;c&&this.engine._pushEvalContext(this._localScope);let f=this.engine,p;try{let d={numericApproximation:t,engine:f,signal:n?.signal,materialization:n?.materialization};p=i.evaluateAsync?.(s,d)??i.evaluate?.(s,d)}finally{c&&this.engine._popEvalContext()}return Promise.resolve(p).then(d=>{let g=d??(c&&i.evaluate===void 0&&i.evaluateAsync===void 0&&this.isCanonical&&s.every((h,b)=>h===this._ops[b])?this:f.function(this._operator,s));return t?qv(f,this._operator,s,g):g})}}};function fd(e,n,t){return!!(n&&(e==="Add"||e==="Multiply")||(e==="Add"||e==="Multiply")&&t.some(i=>i.type.matches("matrix"))||(e==="Add"||e==="Multiply"||e==="Negate"||e==="Subtract"||e==="Divide")&&t.some(i=>Ye(i))||(e==="Equal"||e==="NotEqual")&&t.filter(i=>i.isCollection||bi(i)).length>=2)}var GZ=new Set(["And","Or","Not","Xor","Nand","Nor","Implies","Equivalent"]);function UZ(e,n,t,i,r){let o=i?t.map(s=>s.evaluate(r)):t;if(o.some(s=>m(s,"When"))){let s=[],a=o.map(c=>m(c,"When")?(s.push(c.op2),c.op1):c),u=s.length===1?s[0]:e._fn("And",s),l=e._fn(n,a).evaluate(r);return e._fn("When",[l,u]).evaluate(r)}if(o.some(s=>m(s,"Which"))){let s=o.map(c=>{if(m(c,"Which")){let f=[],p=c.ops;for(let d=0;d+1<p.length;d+=2)f.push({cond:p[d],value:p[d+1]});return f}return[{cond:null,value:c}]}),a=1;for(let c of s)a*=c.length;if(a>16)return;let u=[{conds:[],value:[]}];for(let c of s){let f=[];for(let p of u)for(let d of c)f.push({conds:d.cond?[...p.conds,d.cond]:p.conds,value:[...p.value,d.value]});u=f}let l=[];for(let c of u){let f=c.conds.length===0?e.True:c.conds.length===1?c.conds[0]:e._fn("And",c.conds);l.push(f,e._fn(n,c.value).evaluate(r))}return e._fn("Which",l).evaluate(r)}if(i)return e._fn(n,o).evaluate(r)}function ZZ(e){if(!e.isValid)return"error";if(e.operator==="Function"){let t=e.ops[0],i=ha(e),r=Uc(e),o=`${t.type}`;r===void 0&&i.length>0&&t.type.matches("finite_number")&&!i.every(a=>a.type!==void 0&&$(a.type,"finite_number"))&&(o="number");let s=i.map(a=>a.type!==void 0?`${a.name}: ${le(a.type)}`:"unknown").join(", ");return Y(`(${s}) -> ${o}`,e.engine._typeResolver)}let n=e.operatorDefinition;if(n){let t=n.signature instanceof Z?n.signature.type:typeof n.signature=="string"?Y(n.signature,e.engine._typeResolver):n.signature,i=bn(t)??"unknown";if(typeof n.type=="function"){let r=n.type(e.ops,{engine:e.engine});r&&(r instanceof Z?i=r.type:i=Y(r,e.engine._typeResolver)??i)}else if(e.ops.length>0&&(i==="number"||i==="finite_number")){let r=e.ops.map(o=>o.type.type);if(e.ops.every(o=>o.isFinite===!0)&&r.every(o=>typeof o=="string"&&Su.includes(o))){let o=Te(...r);typeof o=="string"&&$(o,i)&&(i=o)}}if(n.broadcastable){let r=e.ops.some(s=>W(s));if(!((e.operator==="Equal"||e.operator==="NotEqual")&&e.ops.filter(s=>s.isCollection||ds(s)).length>=2)&&!fd(e.operator,r,e.ops)){let a=(e.operator==="Add"||e.operator==="Multiply"||e.operator==="Negate")&&($(i,"collection")||typeof i!="string"&&i.kind==="union"&&i.types.some(u=>$(u,"collection")));if(e.ops.some(u=>Re(u)&&!Ye(u)||Xd(u)||!a&&eI(u)))return Tu(Mu(i));if(e.ops.some(u=>bi(u)))return{kind:"broadcastable",elements:Mu(i)}}}if(n instanceof yi&&n._isLambda&&cu(n)){if(n.inferredSignature&&e.ops.some(r=>Nt(r)))return"any";if(e.ops.some(r=>Re(r)&&!Ye(r)))return Tu(i);if(e.ops.some(r=>bi(r)))return{kind:"broadcastable",elements:i}}return i}if(e.valueDefinition){let t=e.valueDefinition.type.type,i=bn(t)??"unknown";if(cu(t)){if(e.valueDefinition.inferredType&&e.ops.some(r=>Nt(r)))return"any";if(e.ops.some(r=>Re(r)&&!Ye(r)))return Tu(i);if(e.ops.some(r=>bi(r)))return{kind:"broadcastable",elements:i}}return i}return"unknown"}function y4(e,n){return()=>{if(e._deadline===void 0){e._deadline=Date.now()+e.timeLimit;try{return n()}finally{e._deadline=void 0}}return n()}}function HZ(e,n){return async()=>{if(e._deadline===void 0){e._deadline=Date.now()+e.timeLimit;try{return await n()}finally{e._deadline=void 0}}return n()}}function x4(e,n,t){let i=n.isConstant?n.value:e.engine._getSymbolValue(e.operator);if(i&&!i.type.matches("function"))return i.isValid?e.engine.typeError("function",i.type,i.toString()):e;let r=e.ops.map(a=>a.evaluate(t));if(!i||i.type.isUnknown){let a=e.engine.lookupDefinition(e.operator);return a&&fe(a)?e.engine.function(e.operator,r).evaluate(t):e.engine.function(e.operator,r)}let o=n.type?.type,s=typeof o=="object"&&o.kind==="signature"?o:i.type.type;if(r.some(a=>Re(a)&&!Ye(a))&&cu(s)){let a=ms(r);if(a){let u=[];for(;;){let{done:l,value:c}=a.next();if(l)break;u.push(Xt(i,c,t))}return e.engine._fn("List",u)}}return Xt(i,r,t)}function cu(e){let n=YZ(e)?e.signature?.type:e;return!n||typeof n=="string"||n.kind!=="signature"?!0:[...n.args??[],...n.optArgs??[],...n.variadicArg?[n.variadicArg]:[]].every(i=>eS(i.type))}function YZ(e){return typeof e=="object"&&e!==null&&"signature"in e}function eS(e){return typeof e=="string"?!(e==="collection"||e==="indexed_collection"||e==="list"||e==="tuple"||e==="set"||e==="dictionary"||e==="record"||e==="function"):e.kind==="collection"||e.kind==="indexed_collection"||e.kind==="list"||e.kind==="tuple"||e.kind==="set"||e.kind==="dictionary"||e.kind==="record"||e.kind==="signature"||e.kind==="broadcastable"?!1:e.kind==="union"||e.kind==="intersection"?e.types.every(n=>eS(n)):e.kind==="negation"?eS(e.type):!0}function WZ(e,n,t){if(!e.isValid||t?.materialization===!1||e.isEmptyCollection===void 0)return e;let i=t?.materialization??!1;typeof i=="boolean"&&(i=zZ);let r=e.type.type,o=e.isIndexedCollection||(r==="unknown"||r==="any"||r==="value")&&n.collection?.at!==void 0&&e.nops>0&&e.op1.isIndexedCollection===!0,s=e.isFiniteCollection;if(o&&s){let l=e.count;if(l!==void 0&&l>e.engine.maxCollectionSize)return e}let a=[];if(!e.isEmptyCollection)if(!o||!s){let l=typeof i=="number"?i:i[0],c=e.each();for(let f of c){if(a.length===l){c.next().done||a.push(e.engine.symbol("ContinuationPlaceholder"));break}a.push(f.evaluate(t))}}else{let[l,c]=typeof i=="number"?[Math.ceil(i/2),i-Math.ceil(i/2)]:i,f=1,p=e.each();for(let g of p)if(a.push(g.evaluate(t)),f+=1,f>l)break;if(a.length===0)return e;let d=e.count;if(d===void 0||d<=l)(d===void 0||a.length<d)&&a.push(e.engine.symbol("ContinuationPlaceholder"));else{let g=Math.max(l+1,d-c+1);for(d>l+c&&a.push(e.engine.symbol("ContinuationPlaceholder")),f=g;f<=d;){let h=e.at(f);if(!h)break;a.push(h.evaluate(t)),f+=1}}}if(a.length===0&&e.isEmptyCollection===!1)return e;let u=n.collection?.elttype?.(e);return u&&$(u,"tuple<string, any>")?e.engine.function("Dictionary",a):o?e.engine._fn("List",a):e.engine.function("Set",[...a])}var ea=class e extends Je{_kind="string";[Symbol.toStringTag]="[BoxedString]";_string;_utf8Buffer;_unicodeScalarValues;constructor(n,t,i){super(n,i),this._string=t.normalize()}get json(){return`'${this._string}'`}get hash(){return Fi("String"+this._string)}get operator(){return"String"}get isPure(){return!0}get isCanonical(){return!0}set isCanonical(n){}get value(){return this}get type(){return Z.string}get complexity(){return 19}get string(){return this._string}get buffer(){if(this._utf8Buffer===void 0){let n=new TextEncoder;this._utf8Buffer=n.encode(this._string)}return this._utf8Buffer}get unicodeScalars(){return this._unicodeScalarValues===void 0&&(this._unicodeScalarValues=QZ(this._string)),this._unicodeScalarValues}match(n,t){return Or(n)||(n=this.engine.expr(n,{form:"raw"})),We(n)?{[fn(n)]:this}:n instanceof e&&this._string===n._string?{}:null}};function QZ(e){let n=[];for(let t=0;t<e.length;t++){let i=e.codePointAt(t);n.push(i),i>65535&&t++}return n}var pc=class e extends Je{_kind="dictionary";[Symbol.toStringTag]="[BoxedDictionary]";_keyValues={};_type;constructor(n,t,i){super(n,i?.metadata),t instanceof Je?this._initFromExpression(t):this._initFromRecord(t,i)}_initFromRecord(n,t){for(let i in n){if(typeof i!="string")throw new Error(`Dictionary keys must be strings, but got ${typeof i}`);if(i.length===0)throw new Error("Dictionary keys must not be empty strings");this._keyValues[i]=v4(this.engine,n[i],t)}}_initFromExpression(n){if(n instanceof e){Object.assign(this._keyValues,n._keyValues);return}if(n.operator==="Tuple"||n.operator==="Pair"||n.operator==="KeyValuePair"){if(!m(n))return;if(n.nops!==2)throw new Error(`Expected a key/value pair, got ${n.nops} elements`);let[t,i]=n.ops,r;if(q(t))r=t.string;else if(w(t))r=t.symbol;else throw new Error(`Expected a string key, got ${t.type}`);this._keyValues[r]=i.canonical;return}if(n.operator==="Dictionary"){if(!m(n))return;for(let t of n.ops)if(t.operator==="KeyValuePair"||t.operator==="Pair"||t.operator==="Tuple"){if(!m(t))continue;let[i,r]=t.ops,o;if(q(i))o=i.string;else if(w(i))o=i.symbol;else return;this._keyValues[o]=r.canonical}else throw new Error(`Expected a key/value pair, got ${t.type}`);return}}get json(){return{dict:Object.fromEntries(Object.entries(this._keyValues).map(([n,t])=>[n,E4(t)]))}}get hash(){return Fi("Dictionary"+JSON.stringify(this._keyValues))}get operator(){return"Dictionary"}get type(){if(this._type)return this._type;let n=Te(...Object.values(this._keyValues).map(t=>t.type.type));return this._type=new Z({kind:"dictionary",values:n}),this._type}get isPure(){return!0}get isCanonical(){return!0}set isCanonical(n){}get value(){}get complexity(){return 1e3}get isCollection(){return!0}get isIndexedCollection(){return!1}get isLazyCollection(){return!1}contains(n){}get count(){return Object.keys(this._keyValues).length}get isEmptyCollection(){return Object.keys(this._keyValues).length===0}get isFiniteCollection(){return!0}each(){let n=this.engine;return(function*(t){for(let[i,r]of Object.entries(t._keyValues))yield n.tuple(n.string(i),r)})(this)}get(n){return this._keyValues[n]}has(n){return this._keyValues.hasOwnProperty(n)}get keys(){return Object.keys(this._keyValues)}get entries(){return Object.entries(this._keyValues)}get values(){return Object.values(this._keyValues)}evaluate(n){let t=n?.numericApproximation??!1,i=Object.entries(this._keyValues);if(i.every(([,s])=>KZ(s,t)))return this;let r=this.engine,o=i.map(([s,a])=>r._fn("KeyValuePair",[r.string(s),a.evaluate(n)]));return new e(r,r._fn("Dictionary",o))}match(n,t){if(We(n))return{[fn(n)]:this};if(!(n instanceof e))return null;let i=null,r=Object.keys(n._keyValues);for(let o of r){if(!this._keyValues.hasOwnProperty(o))return null;let s=this._keyValues[o],a=n._keyValues[o];if(!s.match(a))return null;if(We(n._keyValues[o])){let u=fn(n._keyValues[o]);u&&(i={...i??{},[u]:s})}}return i}};function E4(e){return q(e)?e.string:w(e)?e.symbol==="True"?!0:e.symbol==="False"?!1:{sym:e.symbol}:N(e)&&e.type.matches("real")?e.re:m(e,"List")?e.ops.map(E4):e.toMathJson({shorthands:[]})}function KZ(e,n){return q(e)?!0:N(e)?!n||!e.isExact:!1}function v4(e,n,t){if(n==null)return e.Nothing;if(n instanceof Je)return n;if(typeof n=="string")return e.string(n);if(typeof n=="number")return e.number(n,t);if(typeof n=="boolean")return n?e.True:e.False;let i=t?.canonical===!1?"raw":"canonical";if(Array.isArray(n))return e.function("List",n.map(r=>v4(e,r,t)));if(typeof n=="object"){if("num"in n)return e.number(n.num,t);if("str"in n)return e.string(n.str);if("sym"in n)return e.symbol(n.sym,t);if("fn"in n)return e.expr(n,{form:i});if("dict"in n)return new pc(e,n.dict,t)}return e.Nothing}function XZ(e){return e===void 0||e==="canonical"?{canonical:!0,structural:!1}:e==="raw"?{canonical:!1,structural:!1}:e==="structural"?{canonical:!1,structural:!0}:{canonical:e,structural:!1}}function Pb(e){if(!e)return{canonical:!0,structural:!1};let{form:n,canonical:t,structural:i}=e;return n!==void 0?XZ(n):i===!0?{canonical:!1,structural:!0}:t!==void 0?{canonical:t,structural:!1}:{canonical:!0,structural:!1}}function nS(e,n,t){if(n instanceof Je)return n;if(n=_e(n),typeof n=="string")return Yt(e,n,t);if(Array.isArray(n)){let[i,...r]=n;return new Sn(e,i,r.map(o=>nS(e,o,t)),{canonical:!1})}if(typeof n=="object"){if("fn"in n)return nS(e,n.fn,t);if("str"in n)return new ea(e,n.str);if("sym"in n)return Yt(e,n.sym,t);if("num"in n)return Yt(e,n.num,t)}return Yt(e,n,t)}function Rb(e,n,t,i){if(i=i?{...i}:{},"canonical"in i||(i.canonical=!0),!yn(n))throw new Error(`Unexpected operator: "${n}" is not a valid symbol: ${vi(n)}`);let r=i.structural??!1;if(n==="Hold")return new Sn(e,"Hold",[nS(e,t[0],i)],{...i,canonical:!0,structural:r});if(n==="Error"||n==="ErrorCode")return new Sn(e,n,t.map(s=>e.expr(s,{form:"raw"})),{metadata:i?.metadata,canonical:!0});if(n==="Number"&&t.length===1)return Yt(e,t[0],i);if(r===!1&&i.canonical===!0){if((n==="Divide"||n==="Rational")&&t.length===2){let s=jt(t[0]);if(s!==null){let a=jt(t[1]);if(a!==null)return a===0n?s===0n?e.NaN:e.ComplexInfinity:e.number([s,a],i)}n="Divide"}if(n==="Complex"){if(t.length===1){let s=t[0];if(s instanceof Je&&s.isNumberLiteral)return e.number(e.complex(0,s.re),i);let a=ne(t[0]);return a!==null&&a!==0?e.number(e.complex(0,a),i):e.expr(s).mul(e.I)}if(t.length===2){let s=t[0]instanceof Je?t[0]:Yt(e,t[0],i),a=t[1]instanceof Je?t[1]:Yt(e,t[1],i);{let c=S4(s);if(c!==null){let f=S4(a);if(f!==null&&!Ge(f.rational)&&(Ge(c.rational)||c.radical===1&&f.radical===1)&&f.radical<=Se&&c.radical<=Se)return e.number(e._numericValue({rational:c.rational,radical:c.radical,imRational:f.rational,imRadical:f.radical}),i)}}let u=s.re,l=a.re;if(l!==null&&u!==null&&!isNaN(l)&&!isNaN(u)){if(l===0&&u===0)return e.Zero;if(l!==0){let c=s.bignumRe;return e.number(e._numericValue(c!==void 0?{re:c,im:l}:{re:u,im:l}),i)}return Yt(e,t[0],i)}return Yt(e,t[0],i).add(Yt(e,t[1],i).mul(e.I))}throw new Error("Expected one or two arguments with Complex expression")}if(n==="Negate"&&t.length===1){let s=t[0];if(typeof s=="number")return e.number(-s,i);if(s instanceof S)return e.number(s.neg(),i);let a=e.expr(s,i);if(N(a)){let u=a.numericValue;return e.number(typeof u=="number"?-u:u.neg(),i)}t=[a]}}return i.canonical===!0?iH(e,n,t,i.metadata,i.scope):iu(new Sn(e,n,t.map(s=>Yt(e,s,{canonical:i.canonical,structural:r,scope:i.scope})),{metadata:i.metadata,canonical:!1,structural:r,scope:i.scope}),i.canonical??!1,i.scope)}function tS(e){e._inferenceTxDepth+=1}function iS(e){e._inferenceTxDepth-=1,e._inferenceTxDepth===0&&(e._freshlyInferred=null)}var eH=new Set;function Yt(e,n,t){tS(e);try{return nH(e,n,t)}finally{iS(e)}}function nH(e,n,t){if(n==null)return e.error("missing");if(n instanceof je)return oH(e,n);if(n instanceof Je)return iu(n,t?.canonical??!0,t?.scope);t=t?{...t}:{},"canonical"in t||(t.canonical=!0);let i=t.canonical===!0,r=t.structural??!1;if(Array.isArray(n)){if(typeof n[0]!="string"){if(Array.isArray(n[0])||n[0]instanceof Je)return Yt(e,["Apply",...n],t);throw new Error(`The first element of an array should be a string (the function name): ${JSON.stringify(n,void 0,4)}`)}return iu(Rb(e,n[0],n.slice(1),{canonical:i,structural:r,scope:t?.scope}),t?.canonical??!0,t?.scope)}if(typeof n=="number"||n instanceof S||n instanceof L)return e.number(n);if(typeof n=="boolean")return e.symbol(n?"True":"False");if(typeof n=="string"){if(Li(n)){let o=V(n);if(!o||!yn(o))return e.error("invalid-symbol",n);let s=i||t.canonical!==!1;return e.symbol(o,{canonical:s})}return xi(n)?e.number(n):(Bu(n),new ea(e,ce(n)))}if(typeof n=="object"){let o=aI(n)?{latex:n.latex,wikidata:n.wikidata,sourceOffsets:n.sourceOffsets}:void 0;if("fn"in n){let[s,...a]=n.fn;return iu(Rb(e,s,a,{canonical:i,structural:r,metadata:o}),t.canonical,t.scope)}if("str"in n)return new ea(e,n.str,o);if("sym"in n)return e.symbol(n.sym,{canonical:i,metadata:o});if("num"in n)return e.number(n,{canonical:i,metadata:o});if("dict"in n)return new pc(e,n.dict,{canonical:i});throw new Error(`Unexpected MathJSON object: ${JSON.stringify(n,void 0,4)}`)}return e.symbol("Undefined")}function tH(e){if(typeof e=="string"||e.kind!=="signature")return!1;let n=[...e.args?.map(t=>t.type)??[],...e.optArgs?.map(t=>t.type)??[],...e.variadicArg?[e.variadicArg.type]:[]];return n.length===0?!1:n.every(t=>$(t,"number"))}function iH(e,n,t,i,r){let o=rH(e,n,t,i,r);if(o)return o;if(n==="List"){let f=t.map(d=>e.expr(d,{form:"raw"})),p=SM("List",f);return p&&p.dtype?new Pf(e,{ops:Ji(e,f,r),shape:p.shape,dtype:p.dtype},{metadata:i}):new Sn(e,"List",Ji(e,f,r),{canonical:!0})}if(n==="Dictionary"){let f=t.map(p=>e.expr(p,{form:"raw"}));return new pc(e,e._fn("Dictionary",f),{canonical:!0})}let s=Qd(n,r??e.context.lexicalScope);if(!s)return e.declare(n,{type:"function",inferred:!0}),new Sn(e,n,we(fu(e,t)),{metadata:i,canonical:!0});if(ie(s)){let f=we(fu(e,t)),p=s.value.type.type;if(e.strict&&!s.value.inferredType&&typeof p!="string"&&p.kind==="signature"){let d=ti(e,f,p);if(d){let g=d.map((h,b)=>{let y=f[b];return y&&y.isValid&&!h.isValid&&y.freeVariables.length>0?y:h});if(g.some(h=>!h.isValid))return new Sn(e,n,g,{metadata:i,canonical:!0})}}return new Sn(e,n,f,{metadata:i,canonical:!0})}let a=s.operator;if(r??=a.scoped?{parent:e.context.lexicalScope,bindings:new Map}:void 0,a.lazy){let f=t.map(p=>e.expr(p,{form:"raw"}));if(a.canonical){try{if(o=a.canonical(f,{engine:e,scope:r}),o)return o}catch(p){console.error(p instanceof Error?p.message:p)}return o=new Sn(e,n,f,{metadata:i,canonical:!1}),o}return o=new Sn(e,n,a.inferredSignature?f:ti(e,f,a.signature.type,a.lazy,a.broadcastable)??f,{metadata:i,canonical:!0,scope:r}),o}let u=t.map(f=>e.expr(f));if(a.canonical){try{let p=a.canonical(u,{engine:e,scope:r});if(p){if(e.strict&&!a.inferredSignature&&m(p,n)&&p.isValid&&tH(a.signature.type)){let d=Tt(e,p.ops);if(d.some(g=>!g.isValid))return new Sn(e,n,d,{metadata:i,canonical:!0,scope:r})}return p}}catch(p){console.error(p instanceof Error?p.message:p)}return new Sn(e,n,u,{metadata:i,canonical:!1})}let l=we(u,a.associative?n:void 0),c=a.inferredSignature?null:ti(e,l,a.signature.type,a.lazy,a.broadcastable,e._inferenceTxDepth>0?e._freshlyInferred??eH:void 0);if(c){if(c.some(f=>!f.isValid))return new Sn(e,n,c,{metadata:i,canonical:!0,scope:r});l=c}if(l.length===1&&l[0].operator===n){if(a.involution&&m(l[0]))return l[0].op1;if(a.idempotent&&m(u[0]))return new Sn(e,n,u[0].ops,{metadata:i,canonical:!0,scope:r})}return new Sn(e,n,qf(n,l),{metadata:i,canonical:!0,scope:r})}function rH(e,n,t,i,r){let o=[];if(n==="Add"||n==="Multiply")o=Tt(e,fu(e,t,r),{flatten:n});else if(n==="Negate"||n==="Square"||n==="Sqrt"||n==="Exp")o=Tt(e,fu(e,t,r),1);else if(n==="Ln"||n==="Log")o=Tt(e,fu(e,t,r)),o.length===0&&(o=[e.error("missing")]);else if(n==="Power"||n==="Root")o=Tt(e,fu(e,t,r),2);else if(n==="Divide")o=Tt(e,fu(e,t,r)),o.length===0&&(o=[e.error("missing"),e.error("missing")]),o.length===1&&(o=[o[0],e.error("missing")]);else return null;if(!o.every(s=>s.isValid))return new Sn(e,n,o,{metadata:i,canonical:!0});if(n==="Add")return Bi(e,o);if(n==="Negate")return JM(o[0]);if(n==="Multiply")return at(e,o);if(n==="Divide")return o.length===2?$i(...o):o.slice(1).reduce((s,a)=>$i(s,a),o[0]);if(n==="Exp")return Jo(e.E,o[0]);if(n==="Square")return Jo(o[0],e.number(2));if(n==="Power")return Jo(o[0],o[1]);if(n==="Root")return Vo(o[0],o[1]);if(n==="Sqrt")return Vo(o[0],2);if(n==="Ln"||n==="Log"){if(o.length>0){if(N(o[0])&&o[0].isSame(1))return e.Zero;if(o.length===1)return new Sn(e,n,o,{metadata:i,canonical:!0})}return new Sn(e,"Log",o,{metadata:i,canonical:!0})}return null}function S4(e){if(!N(e))return null;let n=e.numericValue;if(typeof n=="number")return Number.isInteger(n)?{rational:[n,1],radical:1}:null;if(n.im!==0)return null;let t=n.asExact;return!(t instanceof Ne)||t.isNaN||t.isPositiveInfinity||t.isNegativeInfinity?null:{rational:t.rational,radical:t.radical}}function oH(e,n){if(n.isZero)return e.Zero;if(n.isOne)return e.One;if(n.isNegativeOne)return e.NegativeOne;if(n.isNaN)return e.NaN;if(n.isNegativeInfinity)return e.NegativeInfinity;if(n.isPositiveInfinity)return e.PositiveInfinity;if(n=n.asExact??n,n.im!==0&&n instanceof Ne)return e.number(n);if(!n.isExact){let o=n.im;return o===0?e.number(n.bignumRe??n.re):n.re===0?e.number(e.complex(0,o)):n.bignumRe!==void 0&&!Fa(n.bignumRe)?Bi(e,[e.number(n.bignumRe),e.number(e.complex(0,o))]):e.number(e.complex(n.re,n.im))}let t=[],i=n;if(i.sign!==0)if(i.radical===1)t.push(e.number(i.rational));else{let o=i.rational,s=e.function("Sqrt",[e.number(i.radical)]);if(wt(o))t.push(s);else{let[a,u]=o;u===1?a===1?t.push(s):t.push(e.function("Multiply",[e.number(a),s])):a===1?t.push(e.function("Divide",[s,e.number(u)])):t.push(e.function("Divide",[e.function("Multiply",[e.number(a),s]),e.number(u)]))}}let r;return n.im===0?t.length===0?e.Zero:(r=t.length===1?t[0]:at(e,t),r):t.length===0?e.number(e.complex(0,n.im)):(r=t.length===1?t[0]:at(e,t),Bi(e,[r,e.number(e.complex(0,n.im))]))}function fu(e,n,t){return n.every(i=>i instanceof Je&&i.isCanonical)?n:n.map(i=>e.expr(i,{scope:t}))}var I4;function T4(e){I4=e}function dc(e,n){let t=e.latexSyntax,i=e.latexOptions;return Object.keys(i).length===0?t.serialize(n):t.serialize(n,{...i})}function _4(e,n,t,i,r){if(N(n)&&n.isNegative){let o=n.numericValue;if(typeof o=="number")return Ce(e,"Subtract",[t,e.number(-o)],i,r);if(n.type.matches("rational"))return Ce(e,"Subtract",[t,e.number(o.neg())],i,r)}return n.operator==="Negate"&&t.operator!=="Negate"&&m(n)?Ce(e,"Subtract",[t,n.op1],i,r):null}function sH(e,n,t,i,r){let o=i.exclude;if(n==="Add"&&t.length===2&&!o.includes("Subtract")){let s=_4(e,t[0],t[1],i,r)??_4(e,t[1],t[0],i,r);if(s)return s}if(n==="Divide"&&t.length===2&&o.includes("Divide"))return Ce(e,"Multiply",[t[0],e._fn("Power",[t[1],e.NegativeOne])],i,r);if(n==="Multiply"&&!o.includes("Negate")&&t[0].im===0&&t[0].re===-1)return t.length===2?Ce(e,"Negate",[t[1]],i):Ce(e,"Negate",[e._fn("Multiply",[...t.slice(1)].sort(Ct))],i,r);if(n==="Multiply"&&!o.includes("Divide")){let s=new I4(e,t,{canonical:!1}).asRationalExpression();if(s.operator==="Divide"){let a=s.ops;return Ce(e,s.operator,a,i,r)}}if(n==="Power"){if(!o.includes("Exp")&&w(t[0],"ExponentialE"))return Ce(e,"Exp",[t[1]],i,r);if(N(t[1])){let s=Q(t[1]);if(s===2&&!o.includes("Square"))return Ce(e,"Square",[t[0]],i,r);if(s!==null&&s<0&&!o.includes("Divide"))return Ce(e,"Divide",[e.One,s===-1?t[0]:t[0].pow(-s)],i,r);let a=t[1].re;if(!o.includes("Sqrt")&&a===.5)return Ce(e,"Sqrt",[t[0]],i,r);if(!o.includes("Sqrt")&&a===-.5)return Ce(e,"Divide",[e.One,e._fn("Sqrt",[t[0]])],i,r);if(Mr(a)){let u=uI(a),l=lI(a);if(u===1){if(!o.includes("Sqrt")&&l===2)return Ce(e,"Sqrt",[t[0]],i,r);if(!o.includes("Root"))return Ce(e,"Root",[t[0],e.number(a[1])],i,r)}if(u===-1){if(!o.includes("Sqrt")&&l===2)return Ce(e,"Divide",[e.One,e._fn("Sqrt",[t[0]])],i,r);if(!o.includes("Root"))return Ce(e,"Divide",[e.One,e._fn("Root",[t[0],e.number(a[1])])],i,r)}}}}if(n==="Add"&&t.length===2&&!o.includes("Subtract")){if(N(t[1])){let s=Q(t[1]);if(s!==null&&s<0)return Ce(e,"Subtract",[t[0],e.number(-s)],i,r)}if(m(t[1],"Negate"))return Ce(e,"Subtract",[t[0],t[1].op1],i,r)}if(n==="Tuple"){if(t.length===1&&!o.includes("Single"))return Ce(e,"Single",t,i,r);if(t.length===2&&!o.includes("Pair"))return Ce(e,"Pair",t,i,r);if(t.length===3&&!o.includes("Triple"))return Ce(e,"Triple",t,i,r)}if(n==="Function"&&t.length>0&&m(t[0],"Block")){let s=t[0];if(s.nops===1){let a=t.slice(1);return a.every(u=>w(u)&&/_\d?/.test(u.symbol))?m(s.op1)&&s.op1.ops?.every((u,l)=>w(u)&&w(a[l])&&u.symbol===a[l].symbol)?Ce(e,"Function",[e.symbol(s.op1.operator,{canonical:!1})],i,r):Ce(e,"Function",[s.op1],i,r):Ce(e,"Function",[s.op1,...t.slice(1)],i,r)}}return Ce(e,n,t,i,r)}function Ce(e,n,t,i,r){let o=i.exclude;if(n==="Negate"&&t.length===1&&N(t[0])){let p=t[0].numericValue;if(p!==void 0){if(typeof p=="number")return Ci(e,-p,i);if(p instanceof S||p instanceof L)return Ci(e,p.neg(),i);if(Mr(p))return Ci(e,$t(p),i)}}if(typeof n=="string"&&o.includes(n)){if(n==="Rational"&&t.length===2)return Ce(e,"Divide",t,i,r);if(n==="Complex"&&t.length===2)return Ce(e,"Add",[t[0],e._fn("Multiply",[t[1]??e.symbol("Undefined"),e.I])],i,r);if(n==="Sqrt"&&t.length===1)return Ce(e,"Power",[t[0],o.includes("Half")?e.number([1,2]):e.Half],i,r);if(n==="Root"&&t.length===2&&N(t[1])){let p=Q(t[1]);if(p===2)return Ce(e,"Sqrt",[t[0]],i);if(p!==null)return p<0?Ce(e,"Divide",[e.One,e._fn("Power",[t[0]??e.symbol("Undefined"),e.number([1,-p])])],i,r):Ce(e,"Power",[t[0],e.number([1,-p])],i,r)}if(n==="Square"&&t.length===1)return Ce(e,"Power",[t[0],e.number(2)],i,r);if(n==="Exp"&&t.length===1)return Ce(e,"Power",[e.E,t[0]],i,r);if(n==="Pair"||n=="Single"||n==="Triple")return Ce(e,"Tuple",t,i,r);if(n==="Subtract"&&t.length===2)return Ce(e,"Add",[t[0],e._fn("Negate",[t[1]??e.symbol("Undefined")])],i,r);if(n==="Subtract"&&t.length===1)return Ce(e,"Negate",t,i,r)}let s=n,a=n==="Measurement"?{...i,digits:"max",fractionalDigits:"max"}:i,u=[s,...t.map(p=>p?Db(e,p,a):"Undefined")],l={...r??{}};i.metadata.includes("latex")&&e.latexSyntax?l.latex=l.latex??dc(e,u):l.latex="",i.metadata.includes("wikidata")||(l.wikidata=""),i.metadata.includes("sourceOffsets")||(l.sourceOffsets=void 0);let c=l.sourceOffsets;if(!l.latex&&!l.wikidata&&!c&&i.shorthands.includes("function"))return u;let f={fn:u};return l.latex&&(f.latex=l.latex),l.wikidata&&(f.wikidata=l.wikidata),c&&(f.sourceOffsets=c),f}function aH(e,n){return e=e,n.shorthands.includes("string")?xi(e)||Li(e)?`'${e}'`:e:{str:e}}function na(e,n,t,i){if(n==="Half"&&t.exclude.includes("Half"))return Ci(e,[1,2],t,i);if(i={...i},t.metadata.includes("latex")&&e.latexSyntax?(i.latex=i.latex??dc(e,n),i.latex!==void 0&&(i.latex=i.latex)):i.latex=void 0,t.metadata.includes("wikidata")){if(i.wikidata===void 0){let r=e.lookupDefinition(n);if(r){let o=fe(r)?r.operator.wikidata:r.value.wikidata;o!==void 0&&(i.wikidata=o)}}}else i.wikidata=void 0;return n=n,i.latex===void 0&&i.wikidata===void 0&&t.shorthands.includes("symbol")?Li(n)?n:`\`${n}\``:i.latex!==void 0&&i.wikidata!==void 0?{sym:n,latex:i.latex,wikidata:i.wikidata}:i.latex!==void 0?{sym:n,latex:i.latex}:i.wikidata!==void 0?{sym:n,wikidata:i.wikidata}:{sym:n}}function N4(e,n){if(!n.repeatingDecimal)return e;let[t,i,r,o]=e.match(/^(.*)\.([0-9]+)([e|E][-+]?[0-9]+)?$/)??[];if(!r)return e.toLowerCase();let s=r[r.length-1];r=r.slice(0,-1);let a=16,u="";for(let l=0;l<r.length-a;l++){u=r.substring(0,l);for(let c=0;c<=a;c++){let f=r.substring(l,l+c+1),p=Math.floor((r.length-u.length)/f.length);if(p<3)break;if((u+f.repeat(p+1)).startsWith(r))return f==="0"?s==="0"?i+"."+u+(o??""):e:i+"."+u+"("+f+")"+(o??"")}}for(r+=s;r.endsWith("0");)r=r.slice(0,-1);return typeof n.fractionalDigits=="number"&&n.fractionalDigits>0&&(r=r.slice(0,n.fractionalDigits)),o?`${i}.${r}${o.toLowerCase()}`:`${i}.${r}`}function w4(e){let n=e.digits;if(n!==void 0){if(n==="auto"||n==="max")return n;if(typeof n=="number"&&Number.isFinite(n))return n<0?{significant:Math.max(1,Math.round(-n))}:{fractional:Math.round(n)};if(typeof n=="object"&&n!==null){if("significant"in n&&Number.isFinite(n.significant)&&n.significant>=1)return{significant:Math.round(n.significant)};if("fractional"in n&&Number.isFinite(n.fractional)&&n.fractional>=0)return{fractional:Math.round(n.fractional)}}throw new Error(`Invalid \`digits\` option: ${JSON.stringify(n)}. Expected 'auto', 'max', { significant: n } with n \u2265 1, or { fractional: n } with n \u2265 0.`)}let t=e.fractionalDigits;return t==="auto"||t==="max"?t:typeof t=="number"?t<0?{significant:-t}:{fractional:t}:"max"}function Ci(e,n,t,i){i={...i},t.metadata.includes("latex")||(i.latex=void 0);let r=i.latex===void 0&&i.wikidata===void 0&&!t.metadata.includes("latex")&&t.shorthands.includes("number"),o=t.exclude;if(n instanceof je){if(n.isNaN)return na(e,"NaN",t,i);if(n.isPositiveInfinity)return na(e,"PositiveInfinity",t,i);if(n.isNegativeInfinity)return na(e,"NegativeInfinity",t,i);if(n.isComplexInfinity)return na(e,"ComplexInfinity",t,i);if(r){if(n.isZero)return 0;if(n.isOne)return 1;if(n.isNegativeOne)return-1}if(n instanceof Ne){if(n.im===0&&n.radical===1&&dt(n.rational))return Ci(e,n.rational[0],t);let u=o.includes("Rational"),l=o.includes("Sqrt"),c={...t,digits:"max",fractionalDigits:"max"},f=g=>dt(g)?Ci(e,g[0],c):[u?"Divide":"Rational",Ci(e,g[0],c),Ci(e,g[1],c)],p=g=>l?["Power",g,f([1,2])]:["Sqrt",g],d=(g,h)=>h===1?f(g):wt(g)?p(h):tf(g)?["Negate",p(h)]:g[0]==1?["Divide",p(h),Ci(e,g[1],c)]:g[0]==-1?["Negate",["Divide",p(h),Ci(e,g[1],c)]]:["Multiply",f(g),p(h)];return n.im!==0?["Complex",Ge(n.rational)?0:d(n.rational,n.radical),d(n.imRational,n.imRadical)]:d(n.rational,n.radical)}if(n.im===0){let u=n.bignumRe??n.re;return Ci(e,u,t,i)}return Number.isFinite(n.im)?Ce(e,"Complex",[e.number(n.bignumRe??n.re),e.number(n.im)],t,{...i,wikidata:"Q11567"}):na(e,"ComplexInfinity",t,i)}let s="";if(n instanceof S){let u;if(n.isNaN())u="NaN";else if(!n.isFinite())u=n.isPositive()?"PositiveInfinity":"NegativeInfinity";else{let l=w4(t),c=typeof l=="object"&&"fractional"in l;if(r&&!(typeof l=="object")&&Fa(n))return n.toNumber();if(n.isInteger())c?s=Cr(n,l.fractional):s=(n.significand<0n?-n.significand:n.significand).toString().length+n.exponent-1>20?n.toString():n.toFixed(0);else if(c)s=Cr(n,l.fractional);else{let p;if(l==="max"?p=n.toString():l==="auto"?p=Sa(n,e.precision).toString():p=Sa(n,l.significant).toString(),s=N4(p,t),r){let d=n.toNumber();if(d.toString()===s)return d}}}return t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??dc(e,u??{num:s})),u?i.latex!==void 0?{sym:u,latex:i.latex}:r?u:{sym:u}:i.latex!==void 0?{num:s,latex:i.latex}:r?s:{num:s}}if(n instanceof L)return n.isInfinite()?na(e,"ComplexInfinity",t,i):n.isNaN()?(s="NaN",t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??dc(e,{num:s})),i.latex!==void 0?{num:s,latex:i.latex}:{num:s}):Ce(e,"Complex",[e.number(n.re),e.number(n.im)],t,{...i,wikidata:"Q11567"});if(Mr(n)){let u=!o.includes("Rational");return r&&t.shorthands.includes("function")&&Wn(n)?n[0]===1&&n[1]===2&&!o.includes("Half")?na(e,"Half",t,i):[u?"Rational":"Divide",n[0],n[1]]:Ce(e,u?"Rational":"Divide",[e.number(n[0]),e.number(n[1])],t,{...i})}if(typeof n=="bigint")if(n>=Number.MIN_SAFE_INTEGER&&n<=Number.MAX_SAFE_INTEGER)n=Number(n);else return t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??dc(e,{num:n.toString()})),i.latex!==void 0?{num:n.toString(),latex:i.latex}:r?Mt(n,t.fractionalDigits):{num:Kn(n,t.fractionalDigits)};let a;if(Number.isNaN(n))a="NaN";else if(!Number.isFinite(n))a=n>0?"PositiveInfinity":"NegativeInfinity";else{let u=w4(t);if(typeof u=="object"&&"fractional"in u)s=Cr(n,u.fractional);else{let l=n;typeof u=="object"&&"significant"in u&&!Number.isInteger(n)&&(l=Sa(n,u.significant)),s=N4(l.toString(),t)}}return t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??dc(e,{num:s})),a?i.latex!==void 0?{sym:a,latex:i.latex}:r?a:{sym:a}:i.latex!==void 0?{num:s,latex:i.latex}:r&&s===n.toString()?n:{num:s}}function Db(e,n,t){let i=n.wikidata;if(N(n))return Ci(e,n.numericValue,t,{latex:n.verbatimLatex});if(n.rank>0)return n.json;if(nl(n)&&Array.isArray(n.entries)){if(t.shorthands.includes("dictionary"))return n.json;let r={};for(let[o,s]of n.entries)r[o]=Db(e,s,t);return{dict:r}}if(q(n))return aH(n.string,t);if(w(n))return na(e,n.symbol,t,{latex:n.verbatimLatex,wikidata:i});if(m(n)){let r=n.structural,o=m(r)?r.ops:[];return n.isValid&&(n.isCanonical||n.isStructural)&&t.prettify?sH(e,n.operator,o,t,{latex:n.verbatimLatex,wikidata:i,sourceOffsets:n.sourceOffsets}):Ce(e,n.operator,o,t,{latex:n.verbatimLatex,wikidata:i,sourceOffsets:n.sourceOffsets})}return n.json}function pd(e){if(!bi(e))return!1;let n=e.type.type;return typeof n!="string"&&n.kind==="broadcastable"?!0:e.isCanonical||e.isStructural}var D=class e{static FOLD_OPERAND_PREC=1e3;static WORD_KEYWORD_OPERATORS=new Set(["And","Or","Not"]);static CONTROL_FLOW_HEADS=new Set(["Sequence","Sum","Product","Function","Declare","Assign","Return","Break","Continue","Loop","Comprehension","If","Which","When","Match","Block"]);static BINARY_INFIX_VALUE_OPERATORS=new Set(["Add","Subtract","Multiply","Divide"]);static compileValueOperand(n,t,i=0){let r=e.compile(n,t,i);if(t.bareStatementBlocks&&typeof r=="string"&&r.includes(`
|
|
89
|
-
`)){let o=n!==void 0&&m(n)?n.operator:"?";throw new Error(`${o}: a multi-statement construct (loop-form Sum/Product, Loop, or Block) cannot be used as a sub-expression in "${t.language??"this"}" \u2014 it is only valid as a top-level function body. Fail closed (D6).`)}return r}static compile(n,t,i=0){if(n===void 0)return"";if(!n.isValid)throw new Error(`Cannot compile invalid expression: "${n.toString()}"`);if(w(n)){let r=n.symbol,o=t.operators?.(r);if(o!==void 0){if(!e.BINARY_INFIX_VALUE_OPERATORS.has(r))throw new Error(`${r}: cannot compile as a first-class function \u2014 only the binary arithmetic operators (Add/Subtract/Multiply/Divide) lower to a combiner lambda. Fail closed (D6).`);return`(a,b) => a ${o[0]} b`}let s=t.var?.(r),a=t.userFunctions,u=s===r||t.boundVars?.has(r)===!0||t.varsKeys?.has(r)===!0;if(a&&!u&&!a.misses?.has(r)){let c=e.ensureUserFunctionEmitted(n.engine,r,t);if(c!==void 0)return c;(a.misses??=new Set).add(r)}if(s!==void 0)return s;let l=e.tryFoldKnownSymbol(n.engine,r,t);return l!==void 0?l:t.mangleId?t.mangleId(r):r}if(N(n)){if(n.im!==0){if(!t.complex)throw new Error("Complex numbers are not supported by this target");return t.complex(n.re,n.im)}let r=t.number(n.re);return n.re<0&&(t.operators?.("Negate")?.[1]??14)<i?`(${r})`:r}if(q(n))return t.string(n.string);if(!m(n))throw new Error(`Cannot compile expression: "${n.toString()}"`);return e.compileExpr(n.engine,n.operator,n.ops,i,t)}static compileExpr(n,t,i,r,o){if(t==="Error")throw new Error("Error");if(t==="Sequence")return i.length===0?"":`(${i.map(u=>e.compile(u,o,r)).join(", ")})`;if(t==="Sum"||t==="Product"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):typeof u=="string"?`${u}(${i.map(l=>e.compile(l,o)).join(", ")})`:e.compileLoop(t,i,o)}if(!e.CONTROL_FLOW_HEADS.has(t)){let u=n.lookupDefinition(t);if(fe(u)&&typeof u.operator.compile=="function"){let l=u.operator.compile(i,c=>e.compileValueOperand(c,o),{language:o.language??"javascript"});if(l!=null&&l!=="")return l}}if(o.language==="javascript"){let u=e.tryCompileBroadcast(n,t,i,o);if(u!==null)return u}if(o.language==="javascript"){let u=n.lookupDefinition(t);if((e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(u)&&u.operator.broadcastable===!0&&!mt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t))&&i.some(c=>c.isCollection||c.type.matches("list")||c.type.matches("indexed_collection")||pd(c))){let c=o.operators?.(t),f=c===void 0||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c[0]),p=i.length===1&&fe(u)&&u.operator.broadcastable===!0&&typeof o.functions?.(t)=="function"&&Re(i[0]);if(f&&!p)throw new Error(`${t}: cannot compile scalar arithmetic over a list-valued operand \u2014 the JavaScript compile target has no list-arithmetic support. Fail closed (D6). Materialize the list with evaluate() and compile a scalar element function instead.`)}}if(o.language==="python"){let u=n.lookupDefinition(t),l=e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(u)&&u.operator.broadcastable===!0&&!mt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t),c=o.operators?.(t),f=c!==void 0&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c[0]);if(l&&f&&i.some(p=>p.isCollection||p.type.matches("list")||p.type.matches("indexed_collection")||pd(p)))throw new Error(`${t}: cannot compile arithmetic over a possibly-collection-typed operand on the Python target \u2014 Python's arithmetic operators repeat/concatenate a list instead of broadcasting element-wise, diverging from the interpreter. Fail closed (D6). Materialize the operand with evaluate() and compile a scalar element function instead.`)}let s=o.operators?.(t);if(s!==void 0&&!i.some(l=>e.isComplexValued(l))){let l=/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s[0])&&!e.WORD_KEYWORD_OPERATORS.has(t),c=/^[a-zA-Z_]/.test(s[0]);if(l)return`${s[0]}(${i.map(f=>e.compileValueOperand(f,o)).join(", ")})`;if(i.every(f=>!f.isCollection)){if(mt(t)&&i.length>2){let p=o.chainOp??"&&",d=[],g=i.map((y,x)=>{let E=e.compileValueOperand(y,o,s[1]),v=x>=1&&x<=i.length-2;if(o.bindExpr&&v&&!w(y)&&!N(y)){let _=e.tempVar();return d.push([_,E]),_}return E}),h=[];for(let y=0;y<g.length-1;y++)h.push(`${g[y]} ${s[0]} ${g[y+1]}`);let b=`(${h.join(`) ${p} (`)})`;return d.length>0&&o.bindExpr?o.bindExpr(d,b):b}let f;if(i.length===1){let p=e.compileValueOperand(i[0],o,s[1]),d=!c&&p.length>0&&p[0]===s[0][s[0].length-1],g=c||d?" ":"";f=`${s[0]}${g}${p}`}else{let p=t==="Power",d=t==="Subtract"||t==="Divide";f=i.map((g,h)=>{let b=s[1];return(p&&h<i.length-1||d&&h>0)&&(b=s[1]+1),e.compileValueOperand(g,o,b)}).join(` ${s[0]} `)}return s[1]<r?`(${f})`:f}}if(t==="Function"){let u=o.functions?.(t);if(typeof u=="function")return u(i,c=>e.compileValueOperand(c,o),o);let l=i.slice(1).map(c=>cn(c)||"_");return`((${l.join(", ")}) => ${e.compile(i[0].canonical,{...o,var:c=>l.includes(c)?c:o.var(c),boundVars:e.withBoundNames(o,l)})})`}if(t==="Declare"){let u=w(i[0])?i[0].symbol:"_";if(o.declare)return o.declare(u);let l=e.declareValueOperand(i);return l===void 0?`let ${u}`:`let ${u} = ${e.compile(l,o)}`}if(t==="Assign")return`${w(i[0])?i[0].symbol:"_"} = ${e.compile(i[1],o)}`;if(t==="Return")return`return ${e.compile(i[0],o)}`;if(t==="Break")return"break";if(t==="Continue")return"continue";if(t==="Loop"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileForLoop(i,o)}if(t==="Comprehension"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileComprehension(i,o)}if(t==="If"){if(i.length!==3)throw new Error("If: wrong number of arguments");e.assertScalarCondition(i[0]);let u=o.functions?.(t);return u?typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):`${u}(${i.map(l=>e.compile(l,o)).join(", ")})`:`((${e.compile(i[0],o)}) ? (${e.compile(i[1],o)}) : (${e.compile(i[2],o)}))`}if(t==="Which"){if(i.length<2||i.length%2!==0)throw new Error("Which: expected even number of arguments (condition/value pairs)");let u=o.functions?.(t);if(u)return typeof u=="function"?u(i,c=>e.compileValueOperand(c,o),o):`${u}(${i.map(c=>e.compile(c,o)).join(", ")})`;let l=c=>{if(c>=i.length)return"NaN";let f=i[c],p=i[c+1];return w(f,"True")?`(${e.compile(p,o)})`:`((${e.guardCondition(f,o)}) ? (${e.compile(p,o)}) : ${l(c+2)})`};return l(0)}if(t==="When"){if(i.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");let u=o.functions?.(t);if(u)return typeof u=="function"?u(i,f=>e.compileValueOperand(f,o),o):`${u}(${i.map(f=>e.compile(f,o)).join(", ")})`;if(w(i[1],"True"))return`(${e.compile(i[0],o)})`;if(w(i[1],"False"))return"NaN";let l=e.compile(i[0],o);return`((${e.guardCondition(i[1],o)}) ? (${l}) : NaN)`}if(t==="Match"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileMatchJS(n,i,o)}if(t==="Block")return e.compileBlock(i,o);if(t==="Typed")return e.compile(i[0],o);let a=o.functions?.(t);if(!a){let u=e.tryCompileUserFunction(n,t,i,o);if(u!==void 0)return u;throw new Error(`Unknown operator \`${t}\``)}if(typeof a=="function"){let u=n.lookupDefinition(t);if(fe(u)&&u.operator.broadcastable&&i.length===1&&Re(i[0])){let l=e.tempVar(),c={...o,var:f=>f===l?l:o.var(f),boundVars:e.withBoundNames(o,[l])};return`(${e.compile(i[0],o)}).map((${l}) => ${a([i[0].engine.expr(l)],f=>e.compileValueOperand(f,c),c)})`}return a(i,l=>e.compileValueOperand(l,o),o)}if(o.language!==void 0&&!o.language.startsWith("interval")&&!e.COMPLEX_TRANSPARENT_HEADS.has(t)&&i.some(u=>e.isComplexValued(u)))throw new Error(`${t}: real-only target helper "${a}" cannot represent a complex-valued argument. Fail closed (D6).`);return`${a}(${i.map(u=>e.compileValueOperand(u,o)).join(", ")})`}static COMPLEX_TRANSPARENT_HEADS=new Set(["Real","Imaginary","Argument","Conjugate"]);static SCALAR_ARITHMETIC_HEADS=new Set(["Add","Subtract","Multiply","Divide","Negate","Power"]);static LOGICAL_BROADCAST_HEADS=new Set(["And","Or","Not","Xor","Nand","Nor","Implies","Equivalent"]);static tryCompileBroadcast(n,t,i,r){let o=n.lookupDefinition(t);if(!fe(o)||o.operator.broadcastable!==!0||mt(t)||e.LOGICAL_BROADCAST_HEADS.has(t))return null;let s=r.operators?.(t);if(s!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s[0]))return null;let a=g=>{let h=De(g.type.type);return h===void 0?!1:gi(h)};if(t==="Multiply"){let g=b=>Qt(b)||Nt(b)||b.type.matches("list")||b.type.matches("indexed_collection")||pd(b),h=i.filter(g);if(h.length>=2){if(h.some(pd))return i.some(E=>e.isComplexValued(E)||a(E))?null:`_SYS.mul(${i.map(E=>e.compile(E,r)).join(", ")})`;let b=x=>Qt(x)&&x.shape.length>=2||x.type.matches("matrix");if(h.some(x=>Nt(x))||i.some(b))return null;let y=h.filter(x=>Qt(x)&&x.shape.length===1).map(x=>x.shape[0]);if(y.length>=2&&new Set(y).size>1)return null}}let u=r.functions?.(t);if(typeof u!="function")return null;let l=g=>g.isCollection||g.type.matches("list")||g.type.matches("indexed_collection")||pd(g);if(!i.some(l)||i.some(g=>e.isComplexValued(g)||a(g)))return null;let c=i.map(()=>e.tempVar()),f={...r,var:g=>c.includes(g)?g:r.var(g),boundVars:e.withBoundNames(r,c)},p=u(c.map(g=>n.expr(g)),g=>e.compileValueOperand(g,f),f),d=i.map(g=>e.compile(g,r)).join(", ");return`_SYS.bcast((${c.join(", ")}) => ${p}, ${d})`}static declareValueOperand(n){let t=n.slice(1),i,r=t[t.length-1];return r!==void 0&&Lt(r)&&(i=r.get("value"),t=t.slice(0,-1)),t[1]??i}static compileBlock(n,t){let i=[];for(let a of n)if(m(a,"Declare")){let u=a.ops[0];w(u)&&i.push(u.symbol)}if(n.length===1&&i.length===0)return e.compile(n[0],t);let r={};if(t.declare&&t.language){let u=t.language==="wgsl"?"vec2f":"vec2";for(let l of i)for(let c of n){if(m(c,"Declare")&&w(c.ops[0],l)&&w(c.ops[1],"complex")){r[l]=u;break}if(m(c,"Assign")&&w(c.ops[0],l)){e.isComplexValued(c.ops[1])&&(r[l]=u);break}}}let o={...t,var:a=>i.includes(a)?a:t.var(a),boundVars:e.withBoundNames(t,i)},s=n.filter(a=>!w(a,"Nothing")).flatMap(a=>{if(m(a,"Declare")&&w(a.ops[0])&&t.declare){let u=a.ops[0].symbol,l=t.declare(u,r[u]),c=e.declareValueOperand(a.ops);return c!==void 0?[l,`${u} = ${e.compile(c,o)}`]:[l]}return[e.compile(a,o)]}).filter(a=>a!=="");return s.length===0?"":t.block?t.block(s):(s[s.length-1]=`return ${s[s.length-1]}`,`(() => {${t.ws(`
|
|
90
|
-
`)}${
|
|
89
|
+
`)){let o=n!==void 0&&m(n)?n.operator:"?";throw new Error(`${o}: a multi-statement construct (loop-form Sum/Product, Loop, or Block) cannot be used as a sub-expression in "${t.language??"this"}" \u2014 it is only valid as a top-level function body. Fail closed (D6).`)}return r}static compile(n,t,i=0){if(n===void 0)return"";if(!n.isValid)throw new Error(`Cannot compile invalid expression: "${n.toString()}"`);let r=e._boundVarsCtx;e._boundVarsCtx=t.boundVars??r;try{return e._compileInner(n,t,i)}finally{e._boundVarsCtx=r}}static _boundVarsCtx;static _compileInner(n,t,i=0){if(w(n)){let r=n.symbol,o=t.operators?.(r);if(o!==void 0){if(!e.BINARY_INFIX_VALUE_OPERATORS.has(r))throw new Error(`${r}: cannot compile as a first-class function \u2014 only the binary arithmetic operators (Add/Subtract/Multiply/Divide) lower to a combiner lambda. Fail closed (D6).`);return`(a,b) => a ${o[0]} b`}let s=t.var?.(r),a=t.userFunctions,u=s===r||t.boundVars?.has(r)===!0||t.varsKeys?.has(r)===!0;if(a&&!u&&!a.misses?.has(r)){let c=e.ensureUserFunctionEmitted(n.engine,r,t);if(c!==void 0)return c;(a.misses??=new Set).add(r)}if(s!==void 0)return s;let l=e.tryFoldKnownSymbol(n.engine,r,t);return l!==void 0?l:t.mangleId?t.mangleId(r):r}if(N(n)){if(n.im!==0){if(!t.complex)throw new Error("Complex numbers are not supported by this target");return t.complex(n.re,n.im)}let r=t.number(n.re);return n.re<0&&(t.operators?.("Negate")?.[1]??14)<i?`(${r})`:r}if(q(n))return t.string(n.string);if(!m(n))throw new Error(`Cannot compile expression: "${n.toString()}"`);return e.compileExpr(n.engine,n.operator,n.ops,i,t)}static compileExpr(n,t,i,r,o){if(t==="Error")throw new Error("Error");if(t==="Sequence")return i.length===0?"":`(${i.map(u=>e.compile(u,o,r)).join(", ")})`;if(t==="Sum"||t==="Product"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):typeof u=="string"?`${u}(${i.map(l=>e.compile(l,o)).join(", ")})`:e.compileLoop(t,i,o)}if(!e.CONTROL_FLOW_HEADS.has(t)){let u=n.lookupDefinition(t);if(fe(u)&&typeof u.operator.compile=="function"){let l=u.operator.compile(i,c=>e.compileValueOperand(c,o),{language:o.language??"javascript"});if(l!=null&&l!=="")return l}}if(o.language==="javascript"){let u=e.tryCompileBroadcast(n,t,i,o);if(u!==null)return u}if(o.language==="javascript"){let u=n.lookupDefinition(t);if((e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(u)&&u.operator.broadcastable===!0&&!mt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t))&&i.some(c=>c.isCollection||c.type.matches("list")||c.type.matches("indexed_collection")||pd(c))){let c=o.operators?.(t),f=c===void 0||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c[0]),p=i.length===1&&fe(u)&&u.operator.broadcastable===!0&&typeof o.functions?.(t)=="function"&&Re(i[0]);if(f&&!p)throw new Error(`${t}: cannot compile scalar arithmetic over a list-valued operand \u2014 the JavaScript compile target has no list-arithmetic support. Fail closed (D6). Materialize the list with evaluate() and compile a scalar element function instead.`)}}if(o.language==="python"){let u=n.lookupDefinition(t),l=e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(u)&&u.operator.broadcastable===!0&&!mt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t),c=o.operators?.(t),f=c!==void 0&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c[0]);if(l&&f&&i.some(p=>p.isCollection||p.type.matches("list")||p.type.matches("indexed_collection")||pd(p)))throw new Error(`${t}: cannot compile arithmetic over a possibly-collection-typed operand on the Python target \u2014 Python's arithmetic operators repeat/concatenate a list instead of broadcasting element-wise, diverging from the interpreter. Fail closed (D6). Materialize the operand with evaluate() and compile a scalar element function instead.`)}let s=o.operators?.(t);if(s!==void 0&&!i.some(l=>e.isComplexValued(l))){let l=/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s[0])&&!e.WORD_KEYWORD_OPERATORS.has(t),c=/^[a-zA-Z_]/.test(s[0]);if(l)return`${s[0]}(${i.map(f=>e.compileValueOperand(f,o)).join(", ")})`;if(i.every(f=>!f.isCollection)){if(mt(t)&&i.length>2){let p=o.chainOp??"&&",d=[],g=i.map((y,x)=>{let E=e.compileValueOperand(y,o,s[1]),v=x>=1&&x<=i.length-2;if(o.bindExpr&&v&&!w(y)&&!N(y)){let _=e.tempVar();return d.push([_,E]),_}return E}),h=[];for(let y=0;y<g.length-1;y++)h.push(`${g[y]} ${s[0]} ${g[y+1]}`);let b=`(${h.join(`) ${p} (`)})`;return d.length>0&&o.bindExpr?o.bindExpr(d,b):b}let f;if(i.length===1){let p=e.compileValueOperand(i[0],o,s[1]),d=!c&&p.length>0&&p[0]===s[0][s[0].length-1],g=c||d?" ":"";f=`${s[0]}${g}${p}`}else{let p=t==="Power",d=t==="Subtract"||t==="Divide";f=i.map((g,h)=>{let b=s[1];return(p&&h<i.length-1||d&&h>0)&&(b=s[1]+1),e.compileValueOperand(g,o,b)}).join(` ${s[0]} `)}return s[1]<r?`(${f})`:f}}if(t==="Function"){let u=o.functions?.(t);if(typeof u=="function")return u(i,c=>e.compileValueOperand(c,o),o);let l=i.slice(1).map(c=>cn(c)||"_");return`((${l.join(", ")}) => ${e.compile(i[0].canonical,{...o,var:c=>l.includes(c)?c:o.var(c),boundVars:e.withBoundNames(o,l)})})`}if(t==="Declare"){let u=w(i[0])?i[0].symbol:"_";if(o.declare)return o.declare(u);let l=e.declareValueOperand(i);return l===void 0?`let ${u}`:`let ${u} = ${e.compile(l,o)}`}if(t==="Assign")return`${w(i[0])?i[0].symbol:"_"} = ${e.compile(i[1],o)}`;if(t==="Return")return`return ${e.compile(i[0],o)}`;if(t==="Break")return"break";if(t==="Continue")return"continue";if(t==="Loop"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileForLoop(i,o)}if(t==="Comprehension"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileComprehension(i,o)}if(t==="If"){if(i.length!==3)throw new Error("If: wrong number of arguments");e.assertScalarCondition(i[0]);let u=o.functions?.(t);return u?typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):`${u}(${i.map(l=>e.compile(l,o)).join(", ")})`:`((${e.compile(i[0],o)}) ? (${e.compile(i[1],o)}) : (${e.compile(i[2],o)}))`}if(t==="Which"){if(i.length<2||i.length%2!==0)throw new Error("Which: expected even number of arguments (condition/value pairs)");let u=o.functions?.(t);if(u)return typeof u=="function"?u(i,c=>e.compileValueOperand(c,o),o):`${u}(${i.map(c=>e.compile(c,o)).join(", ")})`;let l=c=>{if(c>=i.length)return"NaN";let f=i[c],p=i[c+1];return w(f,"True")?`(${e.compile(p,o)})`:`((${e.guardCondition(f,o)}) ? (${e.compile(p,o)}) : ${l(c+2)})`};return l(0)}if(t==="When"){if(i.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");let u=o.functions?.(t);if(u)return typeof u=="function"?u(i,f=>e.compileValueOperand(f,o),o):`${u}(${i.map(f=>e.compile(f,o)).join(", ")})`;if(w(i[1],"True"))return`(${e.compile(i[0],o)})`;if(w(i[1],"False"))return"NaN";let l=e.compile(i[0],o);return`((${e.guardCondition(i[1],o)}) ? (${l}) : NaN)`}if(t==="Match"){let u=o.functions?.(t);return typeof u=="function"?u(i,l=>e.compileValueOperand(l,o),o):e.compileMatchJS(n,i,o)}if(t==="Block")return e.compileBlock(i,o);if(t==="Typed")return e.compile(i[0],o);let a=o.functions?.(t);if(!a){let u=e.tryCompileUserFunction(n,t,i,o);if(u!==void 0)return u;throw new Error(`Unknown operator \`${t}\``)}if(typeof a=="function"){let u=n.lookupDefinition(t);if(fe(u)&&u.operator.broadcastable&&i.length===1&&Re(i[0])){let l=e.tempVar(),c={...o,var:f=>f===l?l:o.var(f),boundVars:e.withBoundNames(o,[l])};return`(${e.compile(i[0],o)}).map((${l}) => ${a([i[0].engine.expr(l)],f=>e.compileValueOperand(f,c),c)})`}return a(i,l=>e.compileValueOperand(l,o),o)}if(o.language!==void 0&&!o.language.startsWith("interval")&&!e.COMPLEX_TRANSPARENT_HEADS.has(t)&&i.some(u=>e.isComplexValued(u)))throw new Error(`${t}: real-only target helper "${a}" cannot represent a complex-valued argument. Fail closed (D6).`);return`${a}(${i.map(u=>e.compileValueOperand(u,o)).join(", ")})`}static COMPLEX_TRANSPARENT_HEADS=new Set(["Real","Imaginary","Argument","Conjugate"]);static SCALAR_ARITHMETIC_HEADS=new Set(["Add","Subtract","Multiply","Divide","Negate","Power"]);static LOGICAL_BROADCAST_HEADS=new Set(["And","Or","Not","Xor","Nand","Nor","Implies","Equivalent"]);static tryCompileBroadcast(n,t,i,r){let o=n.lookupDefinition(t);if(!fe(o)||o.operator.broadcastable!==!0||mt(t)||e.LOGICAL_BROADCAST_HEADS.has(t))return null;let s=r.operators?.(t);if(s!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s[0]))return null;let a=g=>{let h=De(g.type.type);return h===void 0?!1:gi(h)};if(t==="Multiply"){let g=b=>Qt(b)||Nt(b)||b.type.matches("list")||b.type.matches("indexed_collection")||pd(b),h=i.filter(g);if(h.length>=2){if(h.some(pd))return i.some(E=>e.isComplexValued(E)||a(E))?null:`_SYS.mul(${i.map(E=>e.compile(E,r)).join(", ")})`;let b=x=>Qt(x)&&x.shape.length>=2||x.type.matches("matrix");if(h.some(x=>Nt(x))||i.some(b))return null;let y=h.filter(x=>Qt(x)&&x.shape.length===1).map(x=>x.shape[0]);if(y.length>=2&&new Set(y).size>1)return null}}let u=r.functions?.(t);if(typeof u!="function")return null;let l=g=>g.isCollection||g.type.matches("list")||g.type.matches("indexed_collection")||pd(g);if(!i.some(l)||i.some(g=>e.isComplexValued(g)||a(g)))return null;let c=i.map(()=>e.tempVar()),f={...r,var:g=>c.includes(g)?g:r.var(g),boundVars:e.withBoundNames(r,c)},p=u(c.map(g=>n.expr(g)),g=>e.compileValueOperand(g,f),f),d=i.map(g=>e.compile(g,r)).join(", ");return`_SYS.bcast((${c.join(", ")}) => ${p}, ${d})`}static declareValueOperand(n){let t=n.slice(1),i,r=t[t.length-1];return r!==void 0&&Lt(r)&&(i=r.get("value"),t=t.slice(0,-1)),t[1]??i}static compileBlock(n,t){let i=[];for(let o of n)if(m(o,"Declare")){let s=o.ops[0];w(s)&&i.push(s.symbol)}if(n.length===1&&i.length===0)return e.compile(n[0],t);let r=new Map;for(let o of i)r.set(o,!1);e._localComplex.push(r);try{for(let u of n)if(m(u,"Declare")&&w(u.ops[0])){let l=u.ops[0].symbol;w(u.ops[1],"complex")&&r.set(l,!0);let c=e.declareValueOperand(u.ops);c!==void 0&&e.isComplexValued(c)&&r.set(l,!0)}else m(u,"Assign")&&w(u.ops[0])&&r.get(u.ops[0].symbol)===!1&&e.isComplexValued(u.ops[1])&&r.set(u.ops[0].symbol,!0);let o={};if(t.declare&&t.language){let u=t.language==="wgsl"?"vec2f":"vec2";for(let l of i)r.get(l)&&(o[l]=u)}let s={...t,var:u=>i.includes(u)?u:t.var(u),boundVars:e.withBoundNames(t,i)},a=n.filter(u=>!w(u,"Nothing")).flatMap(u=>{if(m(u,"Declare")&&w(u.ops[0])&&t.declare){let l=u.ops[0].symbol,c=t.declare(l,o[l]),f=e.declareValueOperand(u.ops);return f!==void 0?[c,`${l} = ${e.compile(f,s)}`]:[c]}return[e.compile(u,s)]}).filter(u=>u!=="");return a.length===0?"":t.block?t.block(a):(a[a.length-1]=`return ${a[a.length-1]}`,`(() => {${t.ws(`
|
|
90
|
+
`)}${a.join(`;${t.ws(`
|
|
91
91
|
`)}`)}${t.ws(`
|
|
92
|
-
`)}})()`)}static compileForLoop(n,t){if(!n[0])throw new Error("Loop: no body");let i=n[0],r=n.slice(1),o=t.language??"";if(r.length===0){if(o==="glsl"||o==="wgsl")throw new Error(`${o.toUpperCase()}: an unbounded Loop(body) is not supported.`);let a=e.compileLoopBody(i,t);return`(() => {${t.ws(`
|
|
92
|
+
`)}})()`)}finally{e._localComplex.pop()}}static compileForLoop(n,t){if(!n[0])throw new Error("Loop: no body");let i=n[0],r=n.slice(1),o=t.language??"";if(r.length===0){if(o==="glsl"||o==="wgsl")throw new Error(`${o.toUpperCase()}: an unbounded Loop(body) is not supported.`);let a=e.compileLoopBody(i,t);return`(() => {${t.ws(`
|
|
93
93
|
`)}while (true) {${t.ws(`
|
|
94
94
|
`)}${a}${t.ws(`
|
|
95
95
|
`)}}${t.ws(`
|
|
@@ -126,9 +126,9 @@ Error in definition of "${i}"`,"",JSON.stringify(r,void 0,4),"",o instanceof Err
|
|
|
126
126
|
${r}++;
|
|
127
127
|
}
|
|
128
128
|
return ${p};
|
|
129
|
-
})()`}static isComplexValued(n){if(N(n))return n.im!==0;if(w(n)){if(n.symbol==="ImaginaryUnit")return!0;let t=n.type;return
|
|
129
|
+
})()`}static _localComplex=[];static isComplexValued(n){if(N(n))return n.im!==0;if(w(n)){if(n.symbol==="ImaginaryUnit")return!0;for(let r=e._localComplex.length-1;r>=0;r--){let s=e._localComplex[r].get(n.symbol);if(s!==void 0)return s}let t=n.type;if(!t)return!1;if(gi(t.type))return!0;if(t.matches("real")||e._boundVarsCtx?.has(n.symbol))return!1;let i=n.engine._getSymbolValue(n.symbol);return i!==void 0?e.isComplexValued(i):!1}if(m(n)){let t=n.type;return gi(t.type)?!0:t.matches("real")?!1:n.ops.some(i=>e.isComplexValued(i))}return!1}static assertScalarBigOpBody(n,t){if(t.type.matches("list")||t.type.matches("indexed_collection"))throw new Error(`${n}: a collection-valued body does not compile \u2014 distribute the element access through the ${n} (At(${n}(\u2026), k) \u2192 ${n}(At(\u2026, k))) or evaluate instead. Fail closed (D6).`)}static isBooleanValued(n){if(w(n,"True")||w(n,"False"))return!0;if(m(n)){let t=n.operator;if(mt(t)||t==="And"||t==="Or"||t==="Not")return!0;let i=n.type;return i?i.matches("boolean"):!1}if(w(n)){let t=n.type;return t?t.matches("boolean"):!1}return!1}static assertScalarCondition(n){if(n.type.matches("collection"))throw new Error("Cannot compile: a branch condition is a collection-valued expression, which is never a scalar boolean. Materialize the collection first. Fail closed (D6).")}static guardCondition(n,t){e.assertScalarCondition(n);let i=e.compile(n,t);return t.assertBoolean&&!e.isBooleanValued(n)?t.assertBoolean(i):i}static isIntegerValued(n){if(N(n))return n.im===0&&Number.isInteger(n.re);let t=n.type;return t?t.matches("integer"):!1}static isNonNegative(n){return N(n)?n.im===0&&n.re>=0:n.isNonNegative===!0}static MATCH_SWITCH_THRESHOLD=8;static isIrrefutableCase(n){return n.tier===3&&!n.hasGuard&&n.rawPatterns!==void 0&&n.rawPatterns.length===1&&We(n.rawPatterns[0])}static matchCaseComparisons(n){return n.tier===0?(n.dispatchKeys??[]).map(t=>({kind:"literal",value:t.value})):n.tests??[]}static compileMatchConstant(n,t,i,r){let o=t.kind==="literal"?t.value:t.expr;if(q(o)){if(!i)throw new Error(`Match: a string constant is not compilable to "${r.language??"this"}" (no string type). Fail closed (D6).`);return e.compile(o,r)}if(t.kind==="pin"&&!(N(o)||q(o)||w(o)&&n.box(o.symbol).isConstant))throw new Error(`Match: pin '== ${o.toString()}' references a runtime value; not compilable. Fail closed (D6).`);return e.compile(o,r)}static matchLeafCondition(n,t,i,r,o,s){let a=e.matchCaseComparisons(t).map(u=>`${i} ${r} ${e.compileMatchConstant(n,u,o,s)}`);return a.length===0?"false":a.length===1?a[0]:`(${a.join(" || ")})`}static compileMatchBody(n,t,i){if(n.captureNames.length===0)return e.compile(n.body.canonical,i);if(n.bodyClosure===void 0||!m(n.bodyClosure))throw new Error("Match: case body is not compilable. Fail closed (D6).");return e.compile(n.bodyClosure.op1,e.matchCaptureTarget(t,i))}static compileMatchGuard(n,t,i){if(!(!n.hasGuard||n.guard===void 0)){if(n.captureNames.length===0)return e.compile(n.guard.canonical,i);if(n.guardClosure===void 0||!m(n.guardClosure))throw new Error("Match: case guard is not compilable. Fail closed (D6).");return e.compile(n.guardClosure.op1,e.matchCaptureTarget(t,i))}}static matchCaptureTarget(n,t){return n===void 0||n.size===0?t:{...t,var:i=>n.get(i)??t.var(i),boundVars:e.withBoundNames(t,[...n.keys()])}}static compileMatchJS(n,t,i){let r=ib(n,t);if(r.errorAlt!==void 0)throw new Error(`Match: an or-alternative binds the name '${r.errorAlt.toString()}'; not compilable. Fail closed (D6).`);let o=e.tempVar(),s=i.ws(`
|
|
130
130
|
`),a=[],u=!1;for(let c of r.segments){if(u)break;if(c.kind==="dispatch"&&e.matchSwitchable(c)){a.push(e.emitMatchSwitch(n,c,o,i));continue}for(let f of c.cases){if(u)break;if(e.isIrrefutableCase(f)){let p=f.captureNames.length===1?new Map([[f.captureNames[0],o]]):void 0;a.push(`return ${e.compileMatchBody(f,p,i)};`),u=!0;break}a.push(e.emitMatchCaseJS(n,f,o,i))}}u||a.push("return NaN;");let l=e.compile(t[0],i);return`((${o}) => {${s}${a.join(s)}${s}})(${l})`}static emitMatchCaseJS(n,t,i,r){if(t.tier===0||t.tier===1){let s=e.matchLeafCondition(n,t,i,"===",!0,r),a=e.compileMatchGuard(t,void 0,r);return`if (${a===void 0?s:`(${s}) && (${a})`}) return ${e.compileMatchBody(t,void 0,r)};`}if(t.tier===2){let s=[],a=new Map;e.walkMatchShape(n,t.shape,i,s,a,r);let u=e.compileMatchGuard(t,a,r);u!==void 0&&s.push(`(${u})`);let l=e.compileMatchBody(t,a,r);return`if (${s.join(" && ")}) return ${l};`}let o=t.rawPatterns?.[0];throw new Error(`Match: pattern '${o?.toString()??"?"}' is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)}static walkMatchShape(n,t,i,r,o,s){if(t.kind==="dict"){let l=t.entries.map(c=>`'${c.key}'`).join(", ");throw new Error(`Match: dictionary pattern {${l}} is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)}r.push(`Array.isArray(${i})`);let a=t.prefix.length+t.suffix.length;t.rest===void 0?r.push(`${i}.length === ${a}`):r.push(`${i}.length >= ${a}`),t.prefix.forEach((l,c)=>e.walkMatchElement(n,l,`${i}[${c}]`,r,o,s));let u=t.suffix.length;if(t.suffix.forEach((l,c)=>e.walkMatchElement(n,l,`${i}[${i}.length - ${u} + ${c}]`,r,o,s)),t.rest!==void 0&&t.rest.key!==null){let l=t.rest.key.replace(/^_+/,"");o.set(l,`${i}.slice(${t.prefix.length}, ${i}.length - ${u})`)}}static walkMatchElement(n,t,i,r,o,s){switch(t.kind){case"ignore":return;case"bind":o.set(t.key.replace(/^_+/,""),i);return;case"literal":r.push(`${i} === ${e.compileMatchConstant(n,{kind:"literal",value:t.value},!0,s)}`);return;case"pin":r.push(`${i} === ${e.compileMatchConstant(n,{kind:"pin",expr:t.expr},!0,s)}`);return;case"shape":e.walkMatchShape(n,t.node,i,r,o,s);return}}static matchSwitchable(n){let t=0;for(let i of n.cases)for(let r of i.dispatchKeys??[]){if(!r.key.startsWith("n:"))return!1;t++}return t>=e.MATCH_SWITCH_THRESHOLD}static emitMatchSwitch(n,t,i,r){let o=r.ws(`
|
|
131
|
-
`),s=new Set,a=[];for(let u of t.cases){let l=[];for(let c of u.dispatchKeys??[]){let f=Number(c.key.slice(2));s.has(f)||(s.add(f),l.push(`case ${f}:`))}l.length!==0&&a.push(`${l.join(" ")} return ${e.compileMatchBody(u,void 0,r)};`)}return`switch (${i}) {${o}${a.join(o)}${o}}`}static compileMatchTernary(n,t,i,r){let o=ib(n,t);if(o.errorAlt!==void 0)throw new Error(`Match: an or-alternative binds the name '${o.errorAlt.toString()}'; not compilable. Fail closed (D6).`);let s=e.compile(t[0],i),a=o.segments.flatMap(l=>l.cases),u=l=>{if(l>=a.length)return r.noMatch;let c=a[l];if(e.isIrrefutableCase(c)){let p=c.captureNames.length===1?new Map([[c.captureNames[0],s]]):void 0;return e.compileMatchBody(c,p,i)}if(c.tier===0||c.tier===1){let p=e.matchLeafCondition(n,c,s,r.eq,r.allowStrings,i),d=e.compileMatchGuard(c,void 0,i),g=d===void 0?p:`(${p}) && (${d})`;return r.ternary(g,e.compileMatchBody(c,void 0,i),u(l+1))}if(c.tier===2)throw new Error(`Match: list/tuple destructuring is not compilable to "${i.language??"this"}". Fail closed (D6).`);let f=c.rawPatterns?.[0];throw new Error(`Match: pattern '${f?.toString()??"?"}' is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)};return u(0)}static tryFoldKnownSymbol(n,t,i){let r=n._getSymbolValue(t);if(r!==void 0)return e.compile(r,i,e.FOLD_OPERAND_PREC)}static userFunctionLiteral(n,t){let i=n.lookupDefinition(t);if(i&&"operator"in i){let o=i.operator._lambdaLiteral;if(o!==void 0&&m(o,"Function"))return o}let r=n._getSymbolValue(t);if(r!==void 0&&m(r,"Function"))return r}static userFunctionName(n){return`_fn_${n.replace(/[^\w$]/g,"_")}`}static tryCompileUserFunction(n,t,i,r){let o=e.ensureUserFunctionEmitted(n,t,r);if(o===void 0)return;let s=i.map(a=>e.compileValueOperand(a,r)).join(", ");return`${o}(${s})`}static ensureUserFunctionEmitted(n,t,i){let r=i.userFunctions;if(!r)return;let o=e.userFunctionLiteral(n,t);if(o===void 0)return;let s=e.userFunctionName(t);if(!r.defs.has(s)){if(r.compiling.has(s))throw new Error(`Recursive user-defined function \`${t}\` cannot be compiled. Fail closed (D6).`);r.compiling.add(s);try{let a=o.ops.slice(1).map(l=>cn(l)||"_"),u=e.compile(o.ops[0].canonical,{...i,var:l=>a.includes(l)?l:i.var(l)});r.defs.set(s,`const ${s} = (${a.join(", ")}) => ${u};`)}finally{r.compiling.delete(s)}}return s}static userFunctionsPreamble(n){let t=n.userFunctions?.defs;return!t||t.size===0?"":[...t.values()].join(`
|
|
131
|
+
`),s=new Set,a=[];for(let u of t.cases){let l=[];for(let c of u.dispatchKeys??[]){let f=Number(c.key.slice(2));s.has(f)||(s.add(f),l.push(`case ${f}:`))}l.length!==0&&a.push(`${l.join(" ")} return ${e.compileMatchBody(u,void 0,r)};`)}return`switch (${i}) {${o}${a.join(o)}${o}}`}static compileMatchTernary(n,t,i,r){let o=ib(n,t);if(o.errorAlt!==void 0)throw new Error(`Match: an or-alternative binds the name '${o.errorAlt.toString()}'; not compilable. Fail closed (D6).`);let s=e.compile(t[0],i),a=o.segments.flatMap(l=>l.cases),u=l=>{if(l>=a.length)return r.noMatch;let c=a[l];if(e.isIrrefutableCase(c)){let p=c.captureNames.length===1?new Map([[c.captureNames[0],s]]):void 0;return e.compileMatchBody(c,p,i)}if(c.tier===0||c.tier===1){let p=e.matchLeafCondition(n,c,s,r.eq,r.allowStrings,i),d=e.compileMatchGuard(c,void 0,i),g=d===void 0?p:`(${p}) && (${d})`;return r.ternary(g,e.compileMatchBody(c,void 0,i),u(l+1))}if(c.tier===2)throw new Error(`Match: list/tuple destructuring is not compilable to "${i.language??"this"}". Fail closed (D6).`);let f=c.rawPatterns?.[0];throw new Error(`Match: pattern '${f?.toString()??"?"}' is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)};return u(0)}static tryFoldKnownSymbol(n,t,i){let r=n._getSymbolValue(t);if(r!==void 0)return e.compile(r,i,e.FOLD_OPERAND_PREC)}static userFunctionLiteral(n,t){let i=n.lookupDefinition(t);if(i&&"operator"in i){let o=i.operator._lambdaLiteral;if(o!==void 0&&m(o,"Function"))return o}let r=n._getSymbolValue(t);if(r!==void 0&&m(r,"Function"))return r}static userFunctionName(n){return`_fn_${n.replace(/[^\w$]/g,"_")}`}static tryCompileUserFunction(n,t,i,r){let o=e.ensureUserFunctionEmitted(n,t,r);if(o===void 0)return;let s=i.map(a=>e.compileValueOperand(a,r)).join(", ");return`${o}(${s})`}static ensureUserFunctionEmitted(n,t,i){let r=i.userFunctions;if(!r)return;let o=e.userFunctionLiteral(n,t);if(o===void 0)return;let s=e.userFunctionName(t);if(!r.defs.has(s)){if(r.compiling.has(s))throw new Error(`Recursive user-defined function \`${t}\` cannot be compiled. Fail closed (D6).`);r.compiling.add(s);try{let a=o.ops.slice(1).map(l=>cn(l)||"_"),u=e.compile(o.ops[0].canonical,{...i,var:l=>a.includes(l)?l:i.var(l),boundVars:e.withBoundNames(i,a)});r.defs.set(s,`const ${s} = (${a.join(", ")}) => ${u};`)}finally{r.compiling.delete(s)}}return s}static userFunctionsPreamble(n){let t=n.userFunctions?.defs;return!t||t.size===0?"":[...t.values()].join(`
|
|
132
132
|
`)+`
|
|
133
133
|
`}static STRUCTURAL_HEADS=new Set(["Sequence","Sum","Product","Function","Declare","Assign","Return","Break","Continue","Loop","Comprehension","If","Which","When","Match","Block","Limits","Element"]);static analyzeReferences(n,t,i){let r=n.engine,o=new Set,s=new Set,a=new Set,u=new Set,l=(f,p)=>{let d=new Set(f);for(let g of p)d.add(g);return d},c=(f,p)=>{if(w(f)){let y=f.symbol;if(p.has(y)||t.operators?.(y)!==void 0)return;if(i?.has(y)){o.add(y);return}if(t.userFunctions!==void 0){let E=e.userFunctionLiteral(r,y);if(E!==void 0){if(!u.has(y)){u.add(y);let v=E.ops.slice(1).map(_=>cn(_)).filter(_=>_!=="");c(E.ops[0],v.length?l(p,v):p)}return}}let x=r._getSymbolValue(y);if(x!==void 0){a.has(y)||(a.add(y),c(x,p));return}o.add(y);return}if(!m(f))return;let d=f.operator,g=f.ops,h=t.userFunctions!==void 0&&!e.STRUCTURAL_HEADS.has(d)&&t.functions?.(d)===void 0&&t.operators?.(d)===void 0?e.userFunctionLiteral(r,d):void 0,b=!1;if(!e.CONTROL_FLOW_HEADS.has(d)&&t.functions?.(d)===void 0&&t.operators?.(d)===void 0&&h===void 0){let y=r.lookupDefinition(d);if(fe(y)&&typeof y.operator.compile=="function")try{let x=y.operator.compile(g,E=>e.compileValueOperand(E,t),{language:t.language??"javascript"});b=x!=null&&x!==""}catch{b=!1}}if(d!=="Error"&&!e.STRUCTURAL_HEADS.has(d)&&t.functions?.(d)===void 0&&t.operators?.(d)===void 0&&h===void 0&&!b&&s.add(d),h!==void 0){if(!u.has(d)){u.add(d);let y=h.ops.slice(1).map(x=>cn(x)).filter(x=>x!=="");c(h.ops[0],y.length?l(p,y):p)}for(let y of g)c(y,p);return}if(d==="Function"){let y=g.slice(1).map(x=>cn(x)).filter(x=>x!=="");c(g[0],y.length?l(p,y):p);return}if(d==="Sum"||d==="Product"||d==="Integrate"||d==="Loop"||d==="Comprehension"){let y=[],x=[];for(let E of g.slice(1))if(m(E)){w(E.ops[0])&&y.push(E.ops[0].symbol);for(let v of E.ops.slice(1))x.push(v)}else x.push(E);c(g[0],y.length?l(p,y):p);for(let E of x)c(E,p);return}if(d==="Block"){let y=[];for(let E of g)m(E,"Declare")&&w(E.ops[0])&&y.push(E.ops[0].symbol);let x=y.length?l(p,y):p;for(let E of g)c(E,x);return}if(d==="Match"){g[0]!==void 0&&c(g[0],p);for(let y of g.slice(1)){if(!m(y,"MatchCase")||y.ops.length<2)continue;let x=y.ops,E=x[0],v=x.length>=3?x[1]:void 0,_=x[x.length-1],{captures:I,pinExprs:T}=E5(E),k=I.length?l(p,I):p;v!==void 0&&c(v,k),c(_,k);for(let A of T)c(A,p)}return}for(let y of g)c(y,p)};return c(n,new Set),{freeSymbols:[...o],unsupported:[...s]}}static withReferences(n,t,i,r){return Object.assign(n,e.analyzeReferences(t,i,r))}static buildInterpreterFallback(n,t,i,r,o){let s=n.engine,a=c=>c.isCollection?[...c.each()].map(a):c.re,u={freeSymbols:[],unsupported:[]};try{r&&(u=e.analyzeReferences(n,r,o))}catch{}return m(n,"Function")?{target:i,success:!1,code:"",calling:"lambda",run:((...f)=>s.function("Apply",[n,...f.map(p=>s.expr(p))]).evaluate().re),error:t,...u}:{target:i,success:!1,code:"",calling:"expression",run:(c=>{s.pushScope();try{if(c&&typeof c=="object")for(let[f,p]of Object.entries(c))s.declare(f,"number"),s.assign(f,p);return a(n.evaluate())}finally{s.popScope()}}),error:t,...u}}static withBoundNames(n,t){let i=t.filter(o=>o!==""&&o!==void 0);if(i.length===0)return n.boundVars;let r=new Set(n.boundVars);for(let o of i)r.add(o);return r}static tempVar(){return`_${Math.random().toString(36).substring(4)}`}static inlineExpression(n,t){if(/^[\p{L}_][\p{L}\p{N}_]*$/u.test(t)||/^[0-9]+$/.test(t))return new Function("x",`return \`${n}\`;`)(t);{let r=e.tempVar();return new Function("x",`return \`(() => { const ${r} = \${x}; return ${n.replace(/\\\${x}/g,r)}; })()\`;`)(t)}}};var uH=new Set(["Sin","Cos","Tan","Cot","Sec","Csc","Haversine"]),lH=new Set(["Arcsin","Arccos","Arctan","Arctan2","Arccot","Arcsec","Arccsc","InverseHaversine"]);function po(e){let n=e.engine,t=n.angularUnit;if(t==="rad")return e;let i=t==="deg"?Math.PI/180:t==="grad"?Math.PI/200:2*Math.PI,r=o=>{if(!m(o))return o;let s=!1,a=o.ops.map(l=>{let c=r(l);return c!==l&&(s=!0),c}),u=o.operator;if(uH.has(u)&&a.length===1)return n.function(u,[n.function("Multiply",[n.number(i),a[0]])]);if(lH.has(u)&&a.length>=1){let l=s?n.function(u,a):o;return n.function("Multiply",[n.number(1/i),l])}return s?n.function(u,a):o};return r(e)}function ta(e){return typeof e=="object"&&e!==null}function M4(e){return typeof e=="number"&&Number.isFinite(e)}function C4(e,n){if(typeof e!="string")throw new Error(`${n.kind} name must be a string`);if(e.length===0)throw new Error(`${n.kind} name must not be empty`);if(e.trim()!==e)throw new Error(`${n.kind} name must not include leading or trailing whitespace`);if(/\s/u.test(e))throw new Error(`${n.kind} name must not include whitespace`);return e}function k4(e){return C4(e,{kind:"compilation target"})}function A4(e){return C4(e,{kind:"library"})}var cH=["getOperators","getFunctions","createTarget","compile"];function R4(e){if(!ta(e))throw new Error("Invalid compilation target: expected an object implementing LanguageTarget");for(let n of cH)if(typeof e[n]!="function")throw new Error(`Invalid compilation target: missing required method "${n}()"`)}function fH(e,n){if(e===void 0)return;if(!Array.isArray(e))throw new Error(`Invalid library "${n}": "requires" must be an array of library names`);let t=new Set;for(let i of e){let r;try{r=A4(i)}catch(o){throw new Error(`Invalid library "${n}": ${o.message}`)}if(t.has(r))throw new Error(`Invalid library "${n}": duplicate dependency "${r}"`);t.add(r)}}function pH(e,n){if(e===void 0)return;let t=Array.isArray(e)?e:[e];for(let i of t)if(!ta(i)||Array.isArray(i))throw new Error(`Invalid library "${n}": "definitions" must be an object or an array of objects`)}function P4(e){if(!ta(e)||Array.isArray(e))throw new Error('Invalid library definition: expected an object with at least a "name" field');let n=A4(e.name);fH(e.requires,n),pH(e.definitions,n)}function dH(e){if(!ta(e))throw new Error("Invalid compile target: expected an object");if(typeof e.var!="function")throw new Error('Invalid compile target: missing required method "var()"');if(typeof e.string!="function")throw new Error('Invalid compile target: missing required method "string()"');if(typeof e.number!="function")throw new Error('Invalid compile target: missing required method "number()"');if(typeof e.ws!="function")throw new Error('Invalid compile target: missing required method "ws()"');if(typeof e.preamble!="string")throw new Error('Invalid compile target: "preamble" must be a string');if(!M4(e.indent))throw new Error('Invalid compile target: "indent" must be a finite number');if(e.operators!==void 0&&typeof e.operators!="function")throw new Error('Invalid compile target: "operators" must be a function');if(e.functions!==void 0&&typeof e.functions!="function")throw new Error('Invalid compile target: "functions" must be a function');if(e.language!==void 0&&typeof e.language!="string")throw new Error('Invalid compile target: "language" must be a string')}function mH(e,n){if(n!==void 0&&(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!M4(n[1])))throw new Error(`Invalid compilation option "operators.${e}": expected [string, number]`)}function gH(e){if(e!==void 0&&typeof e!="function"){if(!ta(e)||Array.isArray(e))throw new Error('Invalid compilation option "operators": expected a function or a record');for(let[n,t]of Object.entries(e))mH(n,t)}}function hH(e){if(e!==void 0){if(!ta(e)||Array.isArray(e))throw new Error('Invalid compilation option "functions": expected a record');for(let[n,t]of Object.entries(e))if(typeof t!="string"&&typeof t!="function")throw new Error(`Invalid compilation option "functions.${n}": expected a string or function`)}}function bH(e){if(e!==void 0){if(!ta(e)||Array.isArray(e))throw new Error('Invalid compilation option "vars": expected a record');for(let[n,t]of Object.entries(e))if(typeof t!="string")throw new Error(`Invalid compilation option "vars.${n}": expected a string`)}}function yH(e){if(e!==void 0&&!Array.isArray(e))throw new Error('Invalid compilation option "imports": expected an array')}function D4(e){if(e!==void 0){if(!ta(e)||Array.isArray(e))throw new Error("Invalid compilation options: expected an object");if(e.to!==void 0&&typeof e.to!="string")throw new Error('Invalid compilation option "to": expected a string');if(e.target!==void 0&&dH(e.target),gH(e.operators),hH(e.functions),bH(e.vars),yH(e.imports),e.preamble!==void 0&&typeof e.preamble!="string")throw new Error('Invalid compilation option "preamble": expected a string');if(e.fallback!==void 0&&typeof e.fallback!="boolean")throw new Error('Invalid compilation option "fallback": expected a boolean');if(e.iterationBudget!==void 0&&(typeof e.iterationBudget!="number"||!(e.iterationBudget>0)))throw new Error('Invalid compilation option "iterationBudget": expected a positive number');if(e.quadrature!==void 0&&e.quadrature!=="adaptive"&&e.quadrature!=="monte-carlo")throw new Error('Invalid compilation option "quadrature": expected "adaptive" or "monte-carlo"')}}function dd(e,n){D4(n);try{if(n?.target){let r=D.compile(po(e),n.target);return D.withReferences({target:n.target.language??"custom",success:!0,code:r},e,n.target,n.vars?new Set(Object.keys(n.vars)):void 0)}let t=n?.to??"javascript",i=e.engine.getCompilationTarget(t);if(!i)throw new Error(`Compilation target "${t}" is not registered. Available targets: ${e.engine.listCompilationTargets().join(", ")}`);return i.compile(e,{operators:n?.operators,functions:n?.functions,vars:n?.vars,imports:n?.imports,preamble:n?.preamble,realOnly:n?.realOnly,iterationBudget:n?.iterationBudget,quadrature:n?.quadrature})}catch(t){if(n?.fallback??!0){let i=t.message;console.warn(`Compilation fallback for "${e.operator}" (target: ${n?.to??"javascript"}): ${i}`);let r=n?.to??"javascript";if(r==="interval-js"){let s=e.engine.getCompilationTarget("interval-js");if(s)return s.compile(e,{vars:n?.vars,fallback:!0})}let o=n?.target??e.engine.getCompilationTarget(r)?.createTarget();return D.buildInterpreterFallback(e,i,r,o,n?.vars?new Set(Object.keys(n.vars)):void 0)}throw t}}zw(Pe);SI(Pe);vI(Db);T4(oi);Vw(dd);NI(me);wI(ae);TI(rn);Yw(ti);function O4(e){let n={And:Tg,Or:Mg,Not:Cg,Equivalent:kg,Implies:Ag,Xor:Rg,Nand:Pg,Nor:Dg}[e.operator];if(!n||!m(e))return;let t=n(e.ops,{engine:e.engine});if(t)return{value:t,because:"logic"}}function L4(e){if(!m(e,"Sum"))return;let n=e.op1,t=e.op2;if(!n||!m(t,"Limits"))return;let i=C(t.op1),r=t.op2,o=t.op3;if(!i||!r||!o)return;let s=e.engine;if(n.operator==="Sum"||n.operator==="Product"){let u=n.simplify();if(!u.isSame(n))return{value:s.function("Sum",[u,t]),because:"simplified nested sum/product"}}if(N(r)&&N(o)){let u=r.numericValue,l=o.numericValue;if(typeof u=="number"&&typeof l=="number"&&Number.isInteger(u)&&Number.isInteger(l)){if(l<u)return{value:s.Zero,because:"empty sum"};if(l===u)return{value:n.subs({[i]:r}).simplify(),because:"single term sum"}}}if(!new Set(n.unknowns).has(i)){let u=o.sub(r).add(s.One).simplify();return N(u)&&u.numericValue!==void 0&&(typeof u.numericValue=="number"?u.numericValue:u.numericValue.re)<=0?{value:s.Zero,because:"empty sum"}:{value:u.mul(n.simplify()),because:"sum of constant"}}if(C(n)===i){let u=r,l=o;return{value:l.mul(l.add(s.One)).sub(u.mul(u.sub(s.One))).div(2).simplify(),because:"triangular number"}}if(m(n,"Power")&&C(n.op1)===i&&n.op2.isSame(2)&&r.isSame(1)){let u=o;return{value:u.mul(u.add(s.One)).mul(u.mul(2).add(s.One)).div(6),because:"sum of squares"}}if(m(n,"Power")&&C(n.op1)===i&&n.op2.isSame(3)&&r.isSame(1)){let u=o;return{value:u.mul(u.add(s.One)).div(2).pow(2),because:"sum of cubes"}}if(m(n,"Power")&&n.op1.isSame(-1)&&C(n.op2)===i&&r.isSame(0)){let u=o;return{value:s.One.add(s.number(-1).pow(u)).div(2),because:"alternating unit series"}}if(m(n,"Multiply")&&r.isSame(0)){let u=!1,l=!1;for(let c of n.ops)m(c,"Power")&&c.op1.isSame(-1)&&C(c.op2)===i?u=!0:C(c)===i&&(l=!0);if(u&&l&&n.ops.length===2){let c=o;return{value:s.function("Multiply",[s.function("Power",[s.number(-1),c]),s.function("Floor",[s.function("Divide",[s.function("Add",[c,s.One]),s.number(2)])])]),because:"alternating linear series"}}}if(m(n,"Add")){let u=null,l=null;for(let c of n.ops)if(!new Set(c.unknowns).has(i))u=u?u.add(c):c;else if(C(c)===i)l=l?l.add(s.One):s.One;else if(m(c,"Multiply")&&c.ops.some(p=>C(p)===i)){let p=c.ops.filter(d=>C(d)!==i);if(p.length===c.ops.length-1){let d=p.length===1?p[0]:s.function("Multiply",p);l=l?l.add(d):d}}else{u=null,l=null;break}if(u!==null&&l!==null){let c=r,f=o;if(r.isSame(0)){let p=s.function("Add",[f,s.One]),d=s.function("Add",[u,s.function("Divide",[s.function("Multiply",[l,f]),s.number(2)])]);return{value:s.function("Multiply",[p,d]),because:"arithmetic progression"}}else{let p=s.function("Add",[s.function("Subtract",[f,c]),s.One]),d=s.function("Divide",[s.function("Add",[c,f]),s.number(2)]),g=s.function("Add",[u,s.function("Multiply",[l,d])]);return{value:s.function("Multiply",[p,g]),because:"arithmetic progression"}}}}if(m(n,"Power")&&C(n.op2)===i&&!new Set(n.op1.unknowns).has(i)){let u=n.op1,l=o;if(r.isSame(0)){let c=s.One.sub(u.pow(l.add(s.One))),f=s.One.sub(u);return{value:c.div(f),because:"geometric series"}}else if(r.isSame(1)){let c=u.sub(u.pow(l.add(s.One))),f=s.One.sub(u);return{value:c.div(f),because:"geometric series"}}}if(m(n,"Binomial")&&r.isSame(0)&&C(n.op2)===i){let u=n.op1;if(u&&o.isSame(u))return{value:s.function("Power",[s.number(2),u]),because:"sum of binomial coefficients"}}if(m(n,"Multiply")&&r.isSame(0)){let u=!1,l=!1,c=null;for(let b of n.ops)m(b,"Binomial")&&C(b.op2)===i?(u=!0,c=b.op1??null):m(b,"Power")&&b.op1.isSame(-1)&&C(b.op2)===i&&(l=!0);if(u&&l&&c&&o.isSame(c)&&c.isGreater(0)===!0)return{value:s.Zero,because:"alternating binomial sum"};let f=!1;c=null,u=!1;for(let b of n.ops)C(b)===i?f=!0:m(b,"Binomial")&&C(b.op2)===i&&(u=!0,c=b.op1??null);if(f&&u&&c&&o.isSame(c)&&n.ops.length===2){let b=c;return{value:s.function("Multiply",[b,s.function("Power",[s.number(2),b.sub(s.One)])]),because:"weighted binomial sum"}}let p=!1;c=null,u=!1;for(let b of n.ops)m(b,"Power")&&C(b.op1)===i&&b.op2.isSame(2)?p=!0:m(b,"Binomial")&&C(b.op2)===i&&(u=!0,c=b.op1??null);if(p&&u&&c&&o.isSame(c)&&n.ops.length===2){let b=c;return{value:s.function("Multiply",[b,b.add(s.One),s.function("Power",[s.number(2),b.sub(s.number(2))])]),because:"weighted squared binomial sum"}}let d=!1;c=null,u=!1;for(let b of n.ops)m(b,"Power")&&C(b.op1)===i&&b.op2.isSame(3)?d=!0:m(b,"Binomial")&&C(b.op2)===i&&(u=!0,c=b.op1??null);if(d&&u&&c&&o.isSame(c)&&n.ops.length===2){let b=c;return{value:s.function("Multiply",[s.function("Power",[b,s.number(2)]),b.add(s.number(3)),s.function("Power",[s.number(2),b.sub(s.number(3))])]),because:"weighted cubed binomial sum"}}let g=!1,h=!1;c=null,u=!1;for(let b of n.ops)m(b,"Power")&&b.op1.isSame(-1)&&C(b.op2)===i?g=!0:C(b)===i?h=!0:m(b,"Binomial")&&C(b.op2)===i&&(u=!0,c=b.op1??null);if(g&&h&&u&&c&&o.isSame(c)&&n.ops.length===3&&c.isGreaterEqual(2)===!0)return{value:s.Zero,because:"alternating weighted binomial sum"}}if(m(n,"Power")&&n.op1.operator==="Binomial"&&m(n.op1)&&n.op2.isSame(2)&&r.isSame(0)){let u=n.op1,l=u.op1,c=u.op2;if(l&&C(c)===i&&o.isSame(l))return{value:s.function("Binomial",[s.function("Multiply",[s.number(2),l]),l]),because:"sum of binomial squares"}}if(m(n,"Multiply")&&n.ops.length===2&&r.isSame(1)){let[u,l]=n.ops;if(C(u)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(f=>C(f)===i)&&l.ops.some(f=>f.isSame(1))||C(l)===i&&u.operator==="Add"&&m(u)&&u.ops.length===2&&u.ops.some(f=>C(f)===i)&&u.ops.some(f=>f.isSame(1))){let f=o;return{value:s.function("Divide",[s.function("Multiply",[f,s.function("Add",[f,s.One]),s.function("Add",[f,s.number(2)])]),s.number(3)]),because:"sum of k*(k+1)"}}}if(m(n,"Divide")&&n.op1.isSame(1)&&n.op2.operator==="Multiply"&&m(n.op2)){let u=n.op2;if(u.ops.length===2){let[l,c]=u.ops;if(r.isSame(1)&&(C(l)===i&&c.operator==="Add"&&m(c)&&c.ops.length===2&&c.ops.some(p=>C(p)===i)&&c.ops.some(p=>p.isSame(1))||C(c)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(p=>C(p)===i)&&l.ops.some(p=>p.isSame(1)))){let p=o;return{value:p.div(p.add(s.One)),because:"partial fractions (telescoping)"}}if(r.isSame(2)&&(C(l)===i&&c.operator==="Add"&&m(c)&&c.ops.length===2&&c.ops.some(p=>C(p)===i)&&c.ops.some(p=>p.isSame(-1))||C(c)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(p=>C(p)===i)&&l.ops.some(p=>p.isSame(-1)))){let p=o;return{value:p.sub(s.One).div(p),because:"partial fractions (telescoping k*(k-1))"}}}}if(m(n,"Multiply")){let u=[],l=[];for(let c of n.ops)new Set(c.unknowns).has(i)?l.push(c):u.push(c);if(u.length>0&&l.length>0){let c=u.length===1?u[0]:s.function("Multiply",u),f=l.length===1?l[0]:s.function("Multiply",l),p=s.function("Sum",[f,t]);return{value:c.mul(p),because:"factor out constant from sum"}}}}function F4(e){if(!m(e,"Product"))return;let n=e.op1,t=e.op2;if(!n||!m(t,"Limits"))return;let i=C(t.op1),r=t.op2,o=t.op3;if(!i||!r||!o)return;let s=e.engine;if(n.operator==="Sum"||n.operator==="Product"){let u=n.simplify();if(!u.isSame(n))return{value:s.function("Product",[u,t]),because:"simplified nested sum/product"}}if(N(r)&&N(o)){let u=r.numericValue,l=o.numericValue;if(typeof u=="number"&&typeof l=="number"&&Number.isInteger(u)&&Number.isInteger(l)){if(l<u)return{value:s.One,because:"empty product"};if(l===u)return{value:n.subs({[i]:r}).simplify(),because:"single term product"}}}if(!new Set(n.unknowns).has(i)){let u=o.sub(r).add(s.One).simplify();return N(u)&&u.numericValue!==void 0&&(typeof u.numericValue=="number"?u.numericValue:u.numericValue.re)<=0?{value:s.One,because:"empty product"}:{value:n.simplify().pow(u),because:"product of constant"}}if(C(n)===i&&r.isSame(1))return{value:s.function("Factorial",[o]),because:"factorial"};if(m(n,"Add")&&n.ops.length===2&&r.isSame(1)){let[u,l]=n.ops,c=null,f=null;if(C(u)===i&&!new Set(l.unknowns).has(i)?(c=u,f=l):C(l)===i&&!new Set(u.unknowns).has(i)&&(c=l,f=u),c&&f){let p=o,d=f;return{value:s.function("Divide",[s.function("Factorial",[s.function("Add",[p,d])]),s.function("Factorial",[d])]),because:"shifted factorial"}}}if(m(n,"Divide")&&r.isSame(1)){let u=n.op1,l=n.op2;if(C(l)===i&&u.operator==="Add"&&m(u)&&u.ops.length===2&&u.ops.some(c=>C(c)===i)&&u.ops.some(c=>c.isSame(1)))return{value:o.add(s.One),because:"telescoping product"}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(2)){let u=!1,l=!1;for(let c of n.ops)c.isSame(1)?u=!0:m(c,"Negate")&&c.op1.operator==="Power"&&m(c.op1)&&C(c.op1.op1)===i&&c.op1.op2.isSame(-2)?l=!0:m(c,"Power")&&C(c.op1)===i&&c.op2.isSame(-2)||m(c,"Multiply")&&c.ops.some(f=>f.isSame(-1))&&c.ops.some(f=>m(f,"Power")&&C(f.op1)===i&&f.op2.isSame(-2))&&(l=!0);if(u&&l){let c=o;return{value:s.function("Divide",[s.function("Add",[c,s.One]),s.function("Multiply",[s.number(2),c])]),because:"Wallis-like product"}}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(1)){let u=!1,l=0,c=0;for(let f of n.ops)if(N(f)&&typeof f.numericValue=="number")c=f.numericValue;else if(m(f,"Multiply")&&f.ops.length===2){let[p,d]=f.ops;N(p)&&typeof p.numericValue=="number"&&C(d)===i?(l=p.numericValue,u=!0):N(d)&&typeof d.numericValue=="number"&&C(p)===i&&(l=d.numericValue,u=!0)}if(u&&l===2&&c===-1){let f=o;return{value:s.function("Factorial2",[s.function("Subtract",[s.function("Multiply",[s.number(2),f]),s.One])]),because:"odd double factorial"}}}if(m(n,"Multiply")&&n.ops.length===2&&r.isSame(1)){let[u,l]=n.ops;if(u.isSame(2)&&C(l)===i||l.isSame(2)&&C(u)===i){let c=o;return{value:s.function("Multiply",[s.function("Power",[s.number(2),c]),s.function("Factorial",[c])]),because:"even double factorial"}}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(0)){let u=null,l=!1;for(let c of n.ops)C(c)===i?l=!0:new Set(c.unknowns).has(i)||(u=c);if(l&&u){let c=o.add(s.One).simplify();return{value:s.function("Pochhammer",[u,c]),because:"rising factorial (Pochhammer)"}}}if(r.isSame(0)){let u=null,l=!1;if(m(n,"Subtract")&&n.ops.length===2){let[c,f]=n.ops;C(f)===i&&!new Set(c.unknowns).has(i)&&(u=c,l=!0)}else if(m(n,"Add")&&n.ops.length===2)for(let c of n.ops)m(c,"Negate")&&C(c.op1)===i?l=!0:new Set(c.unknowns).has(i)||(u=c);if(l&&u){let c=o.add(s.One).simplify();return{value:s.function("Divide",[s.function("Factorial",[u]),s.function("Factorial",[u.sub(c)])]),because:"falling factorial"}}}if(m(n,"Multiply")){let u=[],l=[];for(let c of n.ops)new Set(c.unknowns).has(i)?l.push(c):u.push(c);if(u.length>0&&l.length>0){let c=u.length===1?u[0]:s.function("Multiply",u),f=l.length===1?l[0]:s.function("Multiply",l),p=o.sub(r).add(s.One).simplify(),d=s.function("Product",[f,t]);return{value:c.pow(p).mul(d),because:"factor out constant from product"}}}}var xH=new Set(["Arcsin","Arctan","Arccsc"]),EH=new Set(["Sinh","Tanh","Coth","Csch","Arsinh","Artanh","Arcoth","Arcsch"]),vH=new Set(["Cos","Sec","Cosh","Sech"]);function B4(e){return e===void 0?e:e.because?.startsWith("|")?{...e,purpose:"transform"}:e}function $4(e){return B4(SH(e))}function SH(e){if(!m(e,"Abs"))return;let n=e.op1;if(!n)return;let t=e.engine;if(n.isNonNegative===!0)return{value:n,because:"|x| -> x"};if(n.isNonPositive===!0)return{value:n.neg(),because:"|x| -> -x"};if(n.unknowns.length===0){let r=e.evaluate();if(N(r)&&r.im===0&&!r.isSame(e))return{value:r,because:"|z| -> exact modulus"}}let i=n.operator;if(i==="Negate"&&m(n))return{value:t._fn("Abs",[n.op1]),because:"|-x| -> |x|"};if(i==="Multiply"&&m(n)){let r=n.ops;for(let o=0;o<r.length;o++){let s=r[o];if(s.isNonNegative===!0){let a=r.filter((l,c)=>c!==o),u=a.length===1?a[0]:t._fn("Multiply",a);return{value:s.mul(t._fn("Abs",[u])),because:"|xy| -> x|y| when x >= 0"}}if(s.isNonPositive===!0){let a=r.filter((l,c)=>c!==o),u=a.length===1?a[0]:t._fn("Multiply",a);return{value:s.neg().mul(t._fn("Abs",[u])),because:"|xy| -> -x|y| when x <= 0"}}}if(r.length===2)return{value:t._fn("Abs",[r[0]]).mul(t._fn("Abs",[r[1]])),because:"|xy| -> |x||y|"}}if(i==="Divide"&&m(n)){let r=n.op1,o=n.op2;if(r&&o)return r.isNonNegative===!0?{value:r.div(t._fn("Abs",[o])),because:"|x/y| -> x/|y| when x >= 0"}:r.isNonPositive===!0?{value:r.neg().div(t._fn("Abs",[o])),because:"|x/y| -> -x/|y| when x <= 0"}:o.isNonNegative===!0?{value:t._fn("Abs",[r]).div(o),because:"|x/y| -> |x|/y when y >= 0"}:o.isNonPositive===!0?{value:t._fn("Abs",[r]).neg().div(o),because:"|x/y| -> -|x|/y when y <= 0"}:{value:t._fn("Abs",[r]).div(t._fn("Abs",[o])),because:"|x/y| -> |x|/|y|"}}if(i==="Power"&&m(n)){let r=n.op1,o=n.op2;if(r&&o){if(o.isEven===!0&&Rn(r))return{value:r.pow(o),because:"|x^n| -> x^n when n is even"};if(o.isOdd===!0)return{value:t._fn("Abs",[r]).pow(o),because:"|x^n| -> |x|^n when n is odd"};if(o.isRational===!1)return{value:t._fn("Abs",[r]).pow(o),because:"|x^n| -> |x|^n when n is irrational"};if(o.isRational===!0&&o.isInteger===!1){let s=o.numerator;if(s){if(s.isEven===!0&&Rn(r))return{value:r.pow(o),because:"|x^(p/q)| -> x^(p/q) when p is even"};if(s.isOdd===!0)return{value:t._fn("Abs",[r]).pow(o),because:"|x^(p/q)| -> |x|^(p/q) when p is odd"}}}}}if((xH.has(i)||EH.has(i))&&m(n)){let r=n.op1;if(r)return{value:t._fn(i,[t._fn("Abs",[r])]),because:`|${i}(x)| -> ${i}(|x|) (odd function)`}}}function q4(e){return B4(_H(e))}function _H(e){if(!m(e,"Power"))return;let n=e.op1,t=e.op2;if(!t||!m(n,"Abs"))return;let i=n.op1;if(i&&Rn(i)){if(t.isEven===!0)return{value:i.pow(t),because:"|x|^n -> x^n when n is even"};if(m(t,"Divide")){let r=t.op1,o=t.op2;if(r&&o&&r.isEven===!0&&o.isOdd===!0)return{value:i.pow(t),because:"|x|^(n/m) -> x^(n/m) when n even, m odd"}}if(t.isRational===!0&&t.isInteger===!1){let r=t.numerator;if(r&&r.isEven===!0)return{value:i.pow(t),because:"|x|^(p/q) -> x^(p/q) when p is even"}}}}function V4(e){let n=e.operator;if(!vH.has(n)||!m(e))return;let t=e.op1;if(!m(t,"Abs"))return;let i=t.op1;if(i)return{value:e.engine._fn(n,[i]),because:`${n}(|x|) -> ${n}(x) (even function)`}}function J4(e){let n=e.operator,t=e.engine;if(n==="Multiply"&&m(e)&&e.ops.length===2){let[i,r]=e.ops,o=i.isInfinity===!0,s=r.isInfinity===!0,a=o&&i.isPositive===!0,u=o&&i.isNegative===!0,l=s&&r.isPositive===!0,c=s&&r.isNegative===!0;if(i.isSame(0)&&s)return{value:t.NaN,because:"0 * infinity -> NaN"};if(r.isSame(0)&&o)return{value:t.NaN,because:"infinity * 0 -> NaN"};if(i.isSame(0)&&r.isFinite===!0)return{value:t.Zero,because:"0 * finite -> 0"};if(r.isSame(0)&&i.isFinite===!0)return{value:t.Zero,because:"finite * 0 -> 0"};if(a){if(r.isPositive===!0)return{value:t.PositiveInfinity,because:"+inf * positive -> +inf"};if(r.isNegative===!0)return{value:t.NegativeInfinity,because:"+inf * negative -> -inf"}}if(c){if(i.isPositive===!0)return{value:t.NegativeInfinity,because:"positive * -inf -> -inf"};if(i.isNegative===!0)return{value:t.PositiveInfinity,because:"negative * -inf -> +inf"}}if(u){if(r.isPositive===!0)return{value:t.NegativeInfinity,because:"-inf * positive -> -inf"};if(r.isNegative===!0)return{value:t.PositiveInfinity,because:"-inf * negative -> +inf"}}if(l){if(i.isPositive===!0)return{value:t.PositiveInfinity,because:"positive * +inf -> +inf"};if(i.isNegative===!0)return{value:t.NegativeInfinity,because:"negative * +inf -> -inf"}}}if(n==="Divide"&&m(e)){let i=e.op1,r=e.op2;if(i&&r){let o=i.isInfinity===!0,s=r.isInfinity===!0,a=o&&i.isPositive===!0,u=o&&i.isNegative===!0;if(o&&s)return{value:t.NaN,because:"inf / inf -> NaN"};if(a){if(r.isPositive===!0&&r.isFinite===!0)return{value:t.PositiveInfinity,because:"+inf / positive -> +inf"};if(r.isNegative===!0&&r.isFinite===!0)return{value:t.NegativeInfinity,because:"+inf / negative -> -inf"}}if(u){if(r.isPositive===!0&&r.isFinite===!0)return{value:t.NegativeInfinity,because:"-inf / positive -> -inf"};if(r.isNegative===!0&&r.isFinite===!0)return{value:t.PositiveInfinity,because:"-inf / negative -> +inf"}}}}if(n==="Exp"&&m(e)){let i=e.op1;if(i){if(w(i,"PositiveInfinity"))return{value:t.PositiveInfinity,because:"exp(+inf) -> +inf"};if(w(i,"NegativeInfinity"))return{value:t.Zero,because:"exp(-inf) -> 0"}}}if(n==="Power"&&m(e)){let i=e.op1,r=e.op2;if(i&&r){let o=i.isInfinity===!0,s=r.isInfinity===!0,a=o&&i.isPositive===!0,u=o&&i.isNegative===!0,l=s&&r.isPositive===!0,c=s&&r.isNegative===!0;if(w(i,"ExponentialE")&&l)return{value:t.PositiveInfinity,because:"e^(+inf) -> +inf"};if(w(i,"ExponentialE")&&c)return{value:t.Zero,because:"e^(-inf) -> 0"};if(i.isSame(1)&&r.isFinite===!0)return{value:t.One,because:"1^finite -> 1"};if(r.isSame(0)&&o)return{value:t.NaN,because:"inf^0 -> NaN"};if(r.isSame(0)&&i.isSame(0)===!1&&i.isFinite===!0)return{value:t.One,because:"x^0 -> 1"};if(l){if(i.isGreater(1)===!0)return{value:t.PositiveInfinity,because:"a^+inf -> +inf when a > 1"};if(i.isPositive===!0&&i.isLess(1)===!0)return{value:t.Zero,because:"a^+inf -> 0 when 0 < a < 1"}}if(c){if(i.isGreater(1)===!0)return{value:t.Zero,because:"a^-inf -> 0 when a > 1"};if(i.isPositive===!0&&i.isLess(1)===!0)return{value:t.PositiveInfinity,because:"a^-inf -> +inf when 0 < a < 1"}}if(a&&r.isNegative===!0)return{value:t.Zero,because:"+inf^negative -> 0"};if(u){if(r.isNegative===!0)return{value:t.Zero,because:"-inf^negative -> 0"};if(r.isInteger===!0&&r.isEven===!0)return{value:t.PositiveInfinity,because:"(-inf)^(even integer) -> +inf"};if(r.isInteger===!0&&r.isOdd===!0)return{value:t.NegativeInfinity,because:"(-inf)^(odd integer) -> -inf"};if(r.isRational===!0){let[f,p]=r.numeratorDenominator,d=f.re,g=p.re;if(typeof d=="number"&&typeof g=="number"&&Number.isInteger(d)&&Number.isInteger(g)){let h=d%2===0,b=d%2!==0,y=g%2!==0;if(h&&y)return{value:t.PositiveInfinity,because:"(-inf)^(even/odd) -> +inf"};if(b&&y)return{value:t.NegativeInfinity,because:"(-inf)^(odd/odd) -> -inf (real)"}}}}}}}function j4(e){let n=NH(e);if(n===void 0)return n;let t=n.because;return t==="ln"||t?.startsWith("ln(")||t?.startsWith("log_")?{...n,purpose:"transform"}:n}function NH(e){let n=e.operator,t=e.engine;if(m(e)){if(n==="Ln"){let i=e.op1;if(!i)return;if(i.isSame(0))return{value:t.NegativeInfinity,because:"ln(0) -> -inf"};if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.PositiveInfinity,because:"ln(+inf) -> +inf"};if(i.operator==="Rational"&&i.isRational===!0&&i.isInteger===!1){let r=i.json;if(Array.isArray(r)&&r[0]==="Rational"){let o=r[1],s=r[2];if(o>0&&s>0)return o===1?{value:t._fn("Ln",[t.number(s)]).neg(),because:"ln(1/q) -> -ln(q)"}:{value:t._fn("Ln",[t.number(o)]).sub(t._fn("Ln",[t.number(s)])),because:"ln(p/q) -> ln(p) - ln(q)"}}}if(m(i,"Power")){let r=i.op1,o=i.op2;if(r&&o){if(r.isNonNegative===!0)return{value:o.mul(t._fn("Ln",[r])),because:"ln(x^n) -> n*ln(x)"};if(o.isEven===!0&&Rn(r))return{value:o.mul(t._fn("Ln",[t._fn("Abs",[r])])),because:"ln(x^n) -> n*ln(|x|) when n even"};if(Rn(r)&&io(t,"Ln",r)!==!0)return{value:o.mul(t._fn("Ln",[r])),because:"ln(x^n) -> n*ln(x)"}}}if(m(i,"Power")&&C(i.op1)==="ExponentialE")return{value:i.op2,because:"ln(e^x) -> x"};if(m(i,"Multiply"))for(let r=0;r<i.ops.length;r++){let o=i.ops[r];if(m(o,"Power")&&C(o.op1)==="ExponentialE"){let s=o.op2,a=i.ops.filter((l,c)=>c!==r),u=a.length===1?a[0]:t._fn("Multiply",[...a]);return{value:s.add(t._fn("Ln",[u])),because:"ln(e^x * y) -> x + ln(y)"}}}if(m(i,"Divide")&&i.op1?.operator==="Power"&&m(i.op1)&&C(i.op1.op1)==="ExponentialE")return{value:i.op1.op2.sub(t._fn("Ln",[i.op2])),because:"ln(e^x / y) -> x - ln(y)"};if(m(i,"Divide")){let r=i.op1,o=i.op2;if(r.isPositive===!0&&o.isPositive===!0)return{value:t._fn("Ln",[r]).sub(t._fn("Ln",[o])),because:"ln(x/y) -> ln(x) - ln(y)"}}if(m(i,"Divide")&&i.op2?.operator==="Power"&&m(i.op2)&&C(i.op2.op1)==="ExponentialE")return{value:t._fn("Ln",[i.op1]).sub(i.op2.op2),because:"ln(y / e^x) -> ln(y) - x"}}if(n==="Log"){let i=e.op1,r=e.op2;if(!i)return;let o=!r||C(r)==="Nothing"?t.number(10):r;if(o.isSame(0)||o.isSame(1))return{value:t.NaN,because:"log base 0 or 1 -> NaN"};if(i.isSame(0))return o.isGreater(1)===!0?{value:t.NegativeInfinity,because:"log_c(0) -> -inf when c > 1"}:o.isPositive===!0&&o.isLess(1)===!0?{value:t.PositiveInfinity,because:"log_c(0) -> +inf when 0 < c < 1"}:{value:t.NaN,because:"log_c(0) -> NaN"};if(i.isSame(o)&&o.isInfinity!==!0)return{value:t.One,because:"log_c(c) -> 1"};if(C(i)==="ExponentialE"&&C(o)!=="ExponentialE")return{value:t.One.div(t._fn("Ln",[o])),because:"log_c(e) -> 1/ln(c)"};if(o.isInfinity===!0&&o.isPositive===!0&&i.isInfinity===!0)return{value:t.NaN,because:"log_inf(inf) -> NaN"};if(o.isInfinity===!0&&o.isPositive===!0&&i.isPositive===!0&&i.isSame(1)===!1&&i.isFinite===!0)return{value:t.Zero,because:"log_inf(x) -> 0"};if(i.isInfinity===!0&&i.isPositive===!0&&o.isFinite===!0){if(o.isGreater(1)===!0)return{value:t.PositiveInfinity,because:"log_c(+inf) -> +inf when c > 1"};if(o.isLess(1)===!0&&o.isPositive===!0)return{value:t.NegativeInfinity,because:"log_c(+inf) -> -inf when 0 < c < 1"}}if(m(i,"Power")&&i.op1?.isSame(o))return{value:i.op2,because:"log_c(c^x) -> x"};if(m(i,"Power")&&C(i.op1)==="ExponentialE"&&!C(o)?.match(/ExponentialE/))return{value:i.op2.div(t._fn("Ln",[o])),because:"log_c(e^x) -> x/ln(c)"};if(m(i,"Exp")&&i.op1&&!C(o)?.match(/ExponentialE/))return{value:i.op1.div(t._fn("Ln",[o])),because:"log_c(exp(x)) -> x/ln(c)"};if(m(i,"Power")){let s=i.op1,a=i.op2;if(s&&a){if(s.isNonNegative===!0||Rn(s)&&(a.isOdd===!0||a.isRational===!1)&&io(t,"Ln",s)!==!0)return{value:a.mul(t._fn("Log",[s,o])),because:"log_c(x^n) -> n*log_c(x)"};if(a.isEven===!0&&Rn(s))return{value:a.mul(t._fn("Log",[t._fn("Abs",[s]),o])),because:"log_c(x^n) -> n*log_c(|x|) when n even"};if(a.isRational===!0&&a.isInteger===!1&&Rn(s)){let u=a.json;if(Array.isArray(u)&&u[0]==="Rational"){let l=u[1];return u[2]%2===0||l%2!==0?{value:a.mul(t._fn("Log",[s,o])),because:"log_c(x^{p/q}) -> (p/q)*log_c(x)"}:{value:a.mul(t._fn("Log",[t._fn("Abs",[s]),o])),because:"log_c(x^{p/q}) -> (p/q)*log_c(|x|) when p even"}}}}}if(m(i,"Multiply"))for(let s=0;s<i.ops.length;s++){let a=i.ops[s];if(m(a,"Power")&&a.op1?.isSame(o)){let u=a.op2,l=i.ops.filter((f,p)=>p!==s),c=l.length===1?l[0]:t._fn("Multiply",[...l]);return{value:u.add(t._fn("Log",[c,o])),because:"log_c(c^x * y) -> x + log_c(y)"}}}if(m(i,"Divide")&&i.op1?.operator==="Power"&&m(i.op1)&&i.op1.op1?.isSame(o))return{value:i.op1.op2.sub(t._fn("Log",[i.op2,o])),because:"log_c(c^x / y) -> x - log_c(y)"};if(m(i,"Divide")&&i.op2?.operator==="Power"&&m(i.op2)&&i.op2.op1?.isSame(o))return{value:t._fn("Log",[i.op1,o]).sub(i.op2.op2),because:"log_c(y / c^x) -> log_c(y) - x"};if(m(i,"Divide")){let s=i.op1,a=i.op2;if(s.isPositive===!0&&a.isPositive===!0){let u=C(o)==="Nothing",l=u?t._fn("Log",[s]):t._fn("Log",[s,o]),c=u?t._fn("Log",[a]):t._fn("Log",[a,o]);return{value:l.sub(c),because:"log_c(x/y) -> log_c(x) - log_c(y)"}}}if(m(o,"Divide")&&o.op1?.isSame(1))return{value:t._fn("Log",[i,o.op2]).neg(),because:"log_{1/c}(a) -> -log_c(a)"};if(o.operator==="Rational"){let s=o.json;if(Array.isArray(s)&&s[0]==="Rational"&&s[1]===1)return{value:t._fn("Log",[i,t.number(s[2])]).neg(),because:"log_{1/c}(a) -> -log_c(a)"}}}if(n==="Power"){let i=e.op1,r=e.op2;if(!i||!r)return;if(C(i)==="ExponentialE"&&r.operator==="Ln"&&m(r))return{value:r.op1,because:"e^ln(x) -> x"};if(C(i)==="ExponentialE"&&r.operator==="Log"&&m(r)&&r.op1){let o=r.op2;if(!o||C(o)==="Nothing"||o.isSame(10))return{value:r.op1.pow(t.One.div(t._fn("Ln",[t.number(10)]))),because:"e^log(x) -> x^{1/ln(10)}"};if(o&&C(o)!=="ExponentialE")return{value:r.op1.pow(t.One.div(t._fn("Ln",[o]))),because:"e^log_c(x) -> x^{1/ln(c)}"}}if(C(i)==="ExponentialE"&&r.operator==="Add"&&m(r)){for(let o=0;o<r.ops.length;o++){let s=r.ops[o];if(m(s,"Ln")){let a=r.ops.filter((l,c)=>c!==o),u=a.length===0?t.Zero:a.length===1?a[0]:t._fn("Add",[...a]);return{value:s.op1.mul(t._fn("Exp",[u])),because:"e^(ln(x) + y) -> x * e^y"}}}for(let o=0;o<r.ops.length;o++){let s=r.ops[o];if(!m(s,"Log")||!s.op1)continue;let a=r.ops.filter((p,d)=>d!==o),u=a.length===0?t.Zero:a.length===1?a[0]:t._fn("Add",[...a]),l=s.op2;return{value:(!l||C(l)==="Nothing"||l.isSame(10)?s.op1.pow(t.One.div(t._fn("Ln",[t.number(10)]))):C(l)==="ExponentialE"?s.op1:s.op1.pow(t.One.div(t._fn("Ln",[l])))).mul(i.pow(u)),because:"e^(log_c(x) + y) -> x^{1/ln(c)} * e^y"}}}if(C(i)==="ExponentialE"&&r.operator==="Multiply"&&m(r))for(let o=0;o<r.ops.length;o++){let s=r.ops[o];if(m(s,"Ln")){let a=r.ops.filter((l,c)=>c!==o),u=a.length===1?a[0]:t._fn("Multiply",[...a]);return{value:s.op1.pow(u),because:"e^(ln(x) * y) -> x^y"}}}if(C(i)==="ExponentialE"&&r.operator==="Divide"&&m(r)&&r.op1?.operator==="Ln"&&m(r.op1))return{value:r.op1.op1.pow(t.One.div(r.op2)),because:"e^(ln(x) / y) -> x^(1/y)"};if(m(r,"Log")&&r.op2?.isSame(i))return{value:r.op1,because:"c^log_c(x) -> x"};if(m(r,"Add"))for(let o=0;o<r.ops.length;o++){let s=r.ops[o];if(m(s,"Log")&&s.op2?.isSame(i)){let a=r.ops.filter((l,c)=>c!==o),u=a.length===0?t.Zero:a.length===1?a[0]:t._fn("Add",[...a]);return{value:s.op1.mul(i.pow(u)),because:"c^(log_c(x) + y) -> x * c^y"}}}if(m(r,"Multiply"))for(let o=0;o<r.ops.length;o++){let s=r.ops[o];if(m(s,"Log")&&s.op2?.isSame(i)){let a=r.ops.filter((l,c)=>c!==o),u=a.length===1?a[0]:t._fn("Multiply",[...a]);return{value:s.op1.pow(u),because:"c^(log_c(x) * y) -> x^y"}}}if(m(r,"Divide")&&r.op1?.operator==="Log"&&m(r.op1)&&r.op1.op2?.isSame(i))return{value:r.op1.op1.pow(t.One.div(r.op2)),because:"c^(log_c(x) / y) -> x^(1/y)"}}if(n==="Add"&&e.ops.length>=2){let i=[],r=new Map;for(let o=0;o<e.ops.length;o++){let s=e.ops[o];if(m(s,"Ln"))i.push({index:o,arg:s.op1,positive:!0});else if(m(s,"Negate")){let a=s.op1;if(m(a,"Ln")&&a.op1)i.push({index:o,arg:a.op1,positive:!1});else if(m(a,"Log")&&a.op1&&a.op2){let u=JSON.stringify(a.op2.json);r.has(u)||r.set(u,[]),r.get(u).push({index:o,arg:a.op1,base:a.op2,positive:!1})}}else if(m(s,"Log")&&s.op1&&s.op2){let a=JSON.stringify(s.op2.json);r.has(a)||r.set(a,[]),r.get(a).push({index:o,arg:s.op1,base:s.op2,positive:!0})}}if(i.length>=2&&!i.some(o=>io(t,"Ln",o.arg)===!0||!Rn(o.arg))){let o=t.One,s=t.One;for(let c of i)c.positive?o=o.mul(c.arg):s=s.mul(c.arg);let a=o.div(s),u=new Set(i.map(c=>c.index)),l=[...e.ops].filter((c,f)=>!u.has(f));return l.length===0?{value:t._fn("Ln",[a]),because:"combine ln terms"}:{value:t._fn("Add",[t._fn("Ln",[a]),...l]),because:"combine ln terms"}}for(let[,o]of r)if(o.length>=2&&!o.some(s=>io(t,"Ln",s.arg)===!0||!Rn(s.arg))){let s=t.One,a=t.One;for(let g of o)g.positive?s=s.mul(g.arg):a=a.mul(g.arg);let u=s.div(a),l=new Set(o.map(g=>g.index)),c=[...e.ops].filter((g,h)=>!l.has(h)),f=o[0].base,d=C(f)==="Nothing"?t._fn("Log",[u]):t._fn("Log",[u,f]);return c.length===0?{value:d,because:"combine log terms"}:{value:t._fn("Add",[d,...c]),because:"combine log terms"}}}if(n==="Divide"){let i=e.op1,r=e.op2;if(i&&r){if(m(i,"Log")&&r.operator==="Log"&&m(r)&&i.op2?.isSame(r.op2))return{value:t._fn("Ln",[i.op1]).div(t._fn("Ln",[r.op1])),because:"log_c(a) / log_c(b) -> ln(a) / ln(b)"};if(m(i,"Log")&&r.operator==="Ln"&&m(r)&&i.op1?.isSame(r.op1))return{value:t.One.div(t._fn("Ln",[i.op2])),because:"log_c(a) / ln(a) -> 1/ln(c)"};if(m(i,"Ln")&&r.operator==="Log"&&m(r)&&i.op1?.isSame(r.op1))return{value:t._fn("Ln",[r.op2]),because:"ln(a) / log_c(a) -> ln(c)"};if(m(i,"Ln")&&r.operator==="Ln"&&m(r)){let o=i.op1,s=r.op1;if(o&&s&&o.isInteger===!0&&s.isInteger===!0&&o.isPositive===!0&&s.isPositive===!0){let a=o.re,u=s.re;if(Number.isFinite(a)&&Number.isFinite(u)&&u>1&&a>0){let l=H(o),c=H(s);if(l!==null&&c!==null&&c>1n){let f=Math.log(a)/Math.log(u),p=Math.round(f);for(let d of[p-1,p,p+1])if(!(d<0)&&c**BigInt(d)===l)return{value:t.number(d),because:"ln(a)/ln(b) -> k when a = b^k"}}}}}}}}}function wH(e){if(!m(e,"Add")||e.nops!==2)return;let n=e.engine,[t,i]=e.ops;if(!N(t)||!N(i))return;let r=Ie(t),o=Ie(i),s=!!r&&!o;if(!s&&!(!!o&&!r))return;let u=s?t:i,c=(s?i:t).numericValue;if(!(c instanceof Ne)||c.im!==0)return;let f=c.radical;if(!Number.isInteger(f)||f<=1)return;let p=Number(c.rational[0]),d=Number(c.rational[1]),g=Ie(u),h=Number(g[0])/Number(g[1]);if(!(h>0))return;let b=n.number([p*p*f,d*d]),y=u.mul(u).sub(b),x=y.re;if(x===null||x<0)return;let E=y.sqrt();if(!Ie(E))return;let v=n.number([1,2]),_=u.add(E).mul(v),I=u.sub(E).mul(v),T=_.re,k=I.re;if(T===null||k===null||T<0||k<0)return;let A=p*d<0?-1:1,P=n.function("Sqrt",[_]),B=n.function("Sqrt",[I]),O=n.function("Add",[P,A<0?n.function("Negate",[B]):B]),J=h+p/d*Math.sqrt(f),G=Math.sqrt(T)+A*Math.sqrt(k);if(G>=0&&!(Math.abs(G*G-J)>1e-9*(1+Math.abs(J))))return O}function IH(e){if(!m(e,"Add")||e.nops!==4)return;let n=e.engine,t,i=[];for(let h of e.ops){if(!N(h))return;let b=h.numericValue;if(!(b instanceof Ne)||b.im!==0)return;if(b.radical<=1){if(t)return;t=h}else{if(Number(b.rational[0])!==2||Number(b.rational[1])!==1)return;i.push(b.radical)}}if(!t||i.length!==3)return;let r=t.re;if(r===null||!(r>0))return;let[o,s,a]=i,u=o*s*a,l=Math.sqrt(u);if(!Number.isInteger(l))return;let c=i.map(h=>n.number([l,h])),f=c.reduce((h,b)=>h+(b.re??NaN),0);if(!Number.isFinite(f)||Math.abs(f-r)>1e-9*(1+r))return;let p=n.function("Add",c.map(h=>n.function("Sqrt",[h]))),d=r+2*(Math.sqrt(o)+Math.sqrt(s)+Math.sqrt(a)),g=p.N().re;if(!(g===null||!(g>=0))&&!(Math.abs(g*g-d)>1e-9*(1+Math.abs(d))))return p}function TH(e){if(!m(e,"Add")||e.nops!==2)return;let n=e.engine,[t,i]=e.ops;if(!N(t)||!N(i))return;let r=Ie(t),o=Ie(i),s=r&&!o?t:o&&!r?i:void 0,a=s===t?i:s===i?t:void 0;if(!s||!a)return;let u=Ie(s),l=a.numericValue;if(!u||u[1]!==1||!(l instanceof Ne)||l.im!==0||l.rational[1]!==1||!Number.isInteger(l.radical)||l.radical<=1)return;let c=Number(u[0]),f=Number(l.rational[0]),p=l.radical;if(![c,f,p].every(Number.isSafeInteger))return;let d=c*c-f*f*p;if(!Number.isSafeInteger(d))return;let g=Math.round(Math.cbrt(d));if(BigInt(g)**3n!==BigInt(d))return;let h=Math.min(1e5,Math.ceil(Math.cbrt(Math.abs(c)+Math.abs(f)*Math.sqrt(p)))+2);for(let b=-h;b<=h;b++){if(4*b*b*b-3*g*b!==c)continue;let y=b*b-g;if(y<0||y%p!==0)continue;let x=Math.round(Math.sqrt(y/p));if(x*x*p===y){for(let E of x===0?[0]:[x,-x])if(E*(3*b*b+E*E*p)===f)return n.function("Add",[n.number(b),n.function("Multiply",[n.number(E),n.function("Sqrt",[n.number(p)])])])}}}function z4(e){if(!N(e))return!1;if(Ie(e))return!0;let n=e.numericValue;return n instanceof Ne&&n.im===0}function G4(e){if(!N(e))return!1;let n=e.numericValue;return n instanceof Ne&&n.im===0&&n.radical>1}function rS(e){if(m(e,"Sqrt")&&e.op1)return e.op1;if(N(e)){let n=e.numericValue;if(n instanceof Ne&&n.im===0&&n.radical>1){let t=BigInt(n.rational[0]),i=BigInt(n.rational[1]);if(t>0==i>0){let r=t*t*BigInt(n.radical),o=i*i;return o===1n?e.engine.number(r):e.engine.number([r,o])}}}return null}function MH(e){if(!m(e))return;let n=e.engine,t=e.op1,i=e.op2;if(!t||!i||!m(i,"Add")||i.nops!==2)return;let[r,o]=i.ops;if(!z4(r)||!z4(o)||!G4(r)&&!G4(o))return;let s=n.function("Add",[r.mul(r),o.mul(o).neg()]);if(!N(s)||Ie(s)===null||s.isSame(0))return;let a=n.function("Add",[r,o.neg()]),u=m(a,"Add")?a.ops:[a],l=m(t,"Add")?t.ops:[t],c=[];for(let h of l)for(let b of u)c.push(h.mul(b));let f=n.function("Add",c),p=n.function("Divide",[f,s]),d=e.N().re,g=p.N().re;if(!(d!==null&&g!==null&&Number.isFinite(d)&&Number.isFinite(g)&&Math.abs(d-g)>1e-9*(1+Math.abs(d))))return p}function oS(e){let n=e.operator,t=e.engine;if(n==="Root"&&m(e)){let i=e.op1,r=e.op2;if(!i||!r)return;if(r.isSame(3)){let s=TH(i);if(s)return{value:s,because:"denest \u221B(a+b\u221Ac) -> u+v\u221Ac"}}if(N(i)&&r.isInteger===!0){let s=e.evaluate();if(!s.isSame(e))return{value:s,because:"normalize exact numeric root",purpose:"transform"}}if(r.isSame(0))return{value:t.NaN,because:"root(x, 0) -> NaN"};if(i.isSame(0))return r.isPositive===!0?{value:t.Zero,because:"root(0, n) -> 0 when n > 0"}:{value:t.NaN,because:"root(0, n) -> NaN when n <= 0"};if(i.isSame(1))return{value:t.One,because:"root(1, n) -> 1"};if(i.isInfinity===!0&&i.isPositive===!0){if(r.isPositive===!0)return{value:t.PositiveInfinity,because:"root(+inf, n) -> +inf when n > 0"};if(r.isNegative===!0)return{value:t.Zero,because:"root(+inf, n) -> 0 when n < 0"}}if(r.isOdd===!0&&i.isNegative===!0)return{value:t._fn("Root",[i.neg(),r]).neg(),because:"root(-a, n) -> -root(a, n) when n odd",purpose:"transform"};let o=rS(i);if(o)return{value:o.pow(t.One.div(t.number(2).mul(r))),because:"root(sqrt(x), n) -> x^{1/(2n)}"};if(m(i,"Root")&&i.op1&&i.op2){let s=i.op1,a=i.op2;return{value:s.pow(t.One.div(a.mul(r))),because:"root(root(x, m), n) -> x^{1/(m*n)}"}}if(m(i,"Power")){let s=i.op1,a=i.op2;if(s&&a?.isSame(r)){if(r.isEven===!0)return{value:t._fn("Abs",[s]),because:"root(x^n, n) -> |x| when n even"};if(r.isOdd===!0||s.isNonNegative===!0)return{value:s,because:"root(x^n, n) -> x when n odd"}}if(s&&a){let u=a.div(r);if(r.isEven===!0){if(u.isInteger===!0)return{value:t._fn("Abs",[s]).pow(u),because:"root(x^m, n) -> |x|^{m/n} when m/n is integer"};let l=Ie(u);if(l){let[,c]=l,f=Ie(r);if(f&&Number(c)<Number(f[0]))return{value:t._fn("Abs",[s]).pow(u),because:"root(x^m, n) -> |x|^{m/n}"}}}if(r.isOdd===!0&&a.isInteger===!0)return{value:s.pow(u),because:"root(x^m, n) -> x^{m/n} when n is odd"};if(s.isNonNegative===!0&&u.isInteger===!0)return{value:s.pow(u),because:"root(x^m, n) -> x^{m/n} when x >= 0"}}}if(m(i,"Multiply")&&i.ops.length>=2){let s=r.re;if(s!==void 0&&Number.isInteger(s)&&s>=2){let a=[],u=[];for(let l of i.ops){let c=t._fn("Root",[l,r]),f=oS(c);if(f&&!f.value.isSame(c))u.push(f.value);else{let p=l.re;if(p!==void 0&&p>0){let d=Math.round(Math.pow(p,1/s));if(Math.pow(d,s)===p){u.push(t.number(d));continue}}a.push(l)}}if(u.length>0){let l=u.length===1?u[0]:t._fn("Multiply",u);if(a.length===0)return{value:l,because:"root(product, n) -> factored"};let c=a.length===1?a[0]:t._fn("Multiply",a);return{value:t._fn("Multiply",[l,t._fn("Root",[c,r])]),because:"root(product, n) -> factored"}}}}}if(n==="Sqrt"&&m(e)){let i=e.op1;if(!i)return;if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.PositiveInfinity,because:"sqrt(+inf) -> +inf"};if(i.operator==="Add"){let o=wh(i);if(o!==null){let l=m(o)?o.op1:o;if(Rn(l))return{value:t._fn("Abs",[l]),because:"sqrt(perfect square trinomial) -> |factor|"}}let s=Ih(i);if(s!==null)return{value:t._fn("Sqrt",[s]),because:"sqrt(a\xB2-b\xB2) -> sqrt((a-b)(a+b))"};let a=wH(i);if(a!==void 0)return{value:a,because:"denest \u221A(a+b\u221Ac) -> \u221Ax+\u221Ay"};let u=IH(i);if(u!==void 0)return{value:u,because:"denest \u221A(a+2\u221Ap+2\u221Aq+2\u221Ar) -> \u221Ax+\u221Ay+\u221Az"}}let r=rS(i);if(r)return{value:r.pow(t.number([1,4])),because:"sqrt(sqrt(x)) -> x^{1/4}"};if(m(i,"Root")&&i.op1&&i.op2){let o=i.op1,s=i.op2;return{value:o.pow(t.One.div(t.number(2).mul(s))),because:"sqrt(root(x, n)) -> x^{1/(2n)}"}}if(m(i,"Power")){let o=i.op1,s=i.op2;if(o&&s){if(s.isSame(2)&&o.isNonNegative===!0)return{value:o,because:"sqrt(x^2) -> x when x >= 0"};if(Rn(o)){if(s.isSame(2))return{value:t._fn("Abs",[o]),because:"sqrt(x^2) -> |x|"};if(s.isEven===!0&&s.isPositive===!0)return{value:t._fn("Abs",[o]).pow(s.div(2)),because:"sqrt(x^{2n}) -> |x|^n"};if(s.isOdd===!0&&s.isInteger===!0&&s.isPositive===!0){let a=s.sub(t.One).div(2);if(a.isPositive===!0)return{value:t._fn("Abs",[o]).pow(a).mul(t._fn("Sqrt",[o])),because:"sqrt(x^{2n+1}) -> |x|^n * sqrt(x)"}}}}}if(m(i,"Multiply")){let o=[],s=[];for(let a of i.ops)if(m(a,"Power")&&a.op1&&a.op2&&Rn(a.op1)){let u=a.op1,l=a.op2;if(l.isSame(2))o.push(t._fn("Abs",[u]));else if(l.isEven===!0&&l.isPositive===!0)o.push(t._fn("Abs",[u]).pow(l.div(2)));else if(l.isInteger===!0&&l.isPositive===!0&&l.isOdd===!0){let c=l.sub(t.One).div(2);c.isPositive===!0&&o.push(t._fn("Abs",[u]).pow(c)),s.push(u)}else s.push(a)}else s.push(a);if(o.length>0){let a=o.length===1?o[0]:t._fn("Multiply",o);if(s.length===0)return{value:a,because:"sqrt(a^2 * ...) -> |a| * ..."};let u=s.length===1?s[0]:t._fn("Multiply",s);return{value:a.mul(t._fn("Sqrt",[u])),because:"sqrt(a^2 * b) -> |a| * sqrt(b)"}}}}if(n==="Power"&&m(e)){let i=e.op1,r=e.op2;if(!i||!r)return;if(r.isSame(1))return{value:i,because:"x^1 -> x"};if(i.isSame(0)&&r.isPositive===!0)return{value:t.Zero,because:"0^x -> 0 when x > 0"};if(i.isSame(-1)){let s=Ie(r);if(s){let[a,u]=s,l=Number(a),c=Number(u);if(l%2!==0&&c%2!==0)return{value:t.number(-1),because:"(-1)^{p/q} -> -1 when p,q odd"}}}if(m(i,"Multiply")){let s=Ie(r);if(s){let[a,u]=s,l=Number(a),c=Number(u),f=l%2!==0,p=c%2!==0;if(f&&p){let d=-1;for(let g=0;g<i.ops.length;g++){let h=i.ops[g];if(N(h)&&h.isNegative===!0){d=g;break}}if(d>=0){let h=i.ops[d].neg(),b=i.ops.map((x,E)=>E===d?h:x);return{value:(b.length===1?b[0]:t._fn("Multiply",b)).pow(r).neg(),because:"(-a*b)^{p/q} -> -(a*b)^{p/q} when p,q odd"}}}}}if(m(i,"Multiply")&&r.isInteger===!0){let s=i.ops.map(a=>a.pow(r));return{value:t._fn("Multiply",s),because:"(a*b)^n -> a^n * b^n"}}if(m(i,"Negate")){let s=i.op1;if(r.isEven===!0)return{value:s.pow(r),because:"(-x)^n -> x^n when n is even"};if(r.isOdd===!0)return{value:s.pow(r).neg(),because:"(-x)^n -> -x^n when n is odd"};let a=Ie(r);if(a){let[u,l]=a,c=Number(u),f=Number(l),p=c%2===0,d=c%2!==0,g=f%2!==0;if(p&&g)return{value:s.pow(r),because:"(-x)^{n/m} -> x^{n/m} when n is even and m is odd"};if(d&&g)return{value:s.pow(r).neg(),because:"(-x)^{n/m} -> -x^{n/m} when n and m are odd"}}}let o=rS(i);if(o){if(r.isEven===!0)return{value:o.pow(r.div(2)),because:"sqrt(x)^n -> x^{n/2} when n is even"};if(o.isNonNegative===!0)return{value:o.pow(r.div(2)),because:"sqrt(x)^n -> x^{n/2} when x >= 0"}}if(m(i,"Root")){let s=i.op1,a=i.op2,u=r.div(a);if(u.isInteger===!0||s.isNonNegative===!0)return{value:s.pow(u),because:"root(x, k)^n -> x^{n/k}"}}if(m(i,"Power")){let s=i.op1,a=i.op2;if(s&&a){let u=s.isNonNegative===!0,l=r.isInteger===!0;if(u||l)return{value:s.pow(a.mul(r)),because:"(x^n)^m -> x^{n*m}"}}}if(m(i,"Divide")&&i.op2.isSame(0)===!1){let s=i.op1,a=i.op2;if(m(r,"Negate"))return{value:a.div(s).pow(r.op1),because:"(a/b)^{-n} -> (b/a)^n"};if(r.isSame(-1))return{value:a.div(s),because:"(a/b)^{-1} -> b/a"};if(r.isNegative===!0&&N(r))return{value:a.div(s).pow(r.neg()),because:"(a/b)^{-n} -> (b/a)^n"}}}if(n==="Divide"&&m(e)){let i=e.op1,r=e.op2;if(!i||!r)return;let o=MH(e);if(o!==void 0)return{value:o,because:"rationalize radical denominator"};if(m(i,"Power")&&r.operator==="Power"&&m(r)){let s=i.op1,a=i.op2,u=r.op1,l=r.op2;if(s?.isSame(u)&&a&&l){let c=t.function("Add",[a,l.neg()]);return{value:s.pow(c),because:"a^m / a^n -> a^{m-n}"}}}if(m(i,"Power")&&i.op1.isSame(r)){let s=t.function("Add",[i.op2,t.NegativeOne]);return{value:r.pow(s),because:"a^m / a -> a^{m-1}"}}if(m(r,"Power")&&r.op1.isSame(i)){let s=t.function("Add",[t.One,r.op2.neg()]);return{value:i.pow(s),because:"a / a^n -> a^{1-n}"}}if(m(r,"Power")&&r.op1.isSame(0)===!1){let s=r.op1,a=r.op2;if(m(a,"Negate"))return{value:i.mul(s.pow(a.op1)),because:"a / b^{-n} -> a * b^n"}}if(m(r,"Multiply"))for(let s=0;s<r.ops.length;s++){let a=r.ops[s];if(m(a,"Power")&&a.op1.isSame(0)===!1&&a.op2.operator==="Negate"&&m(a.op2)){let u=a.op1,l=a.op2.op1,c=r.ops.filter((p,d)=>d!==s),f=c.length===1?c[0]:t._fn("Multiply",c);return{value:i.div(f).mul(u.pow(l)),because:"a / (d * b^{-n}) -> (a/d) * b^n"}}}if(m(r,"Power")&&r.op1.operator==="Divide"&&m(r.op1)&&r.op1.op2.isSame(0)!==!0){let s=r.op1.op1,a=r.op1.op2,u=r.op2;return{value:i.mul(a.div(s).pow(u)),because:"a / (b/c)^d -> a * (c/b)^d",purpose:"transform"}}}if(n==="Multiply"&&m(e)&&e.ops.length>=2&&e.ops.length===2){let[i,r]=e.ops;if(m(i,"Power")&&r.operator==="Power"&&m(r)){let o=i.op1,s=i.op2,a=r.op1,u=r.op2;if(o?.isSame(a)&&s&&u){let l=t.function("Add",[s,u]);if(o.isPositive===!0||o.isNegative===!0||l.isNonNegative===!0)return{value:o.pow(l),because:"x^n * x^m -> x^{n+m}"}}}if(m(r,"Power")&&i.isSame(r.op1)&&(i.isPositive===!0||i.isNegative===!0||N(i)))return{value:i.pow(t.function("Add",[r.op2,t.One])),because:"x * x^n -> x^{n+1}"};if(m(i,"Power")&&r.isSame(i.op1)&&(r.isPositive===!0||r.isNegative===!0||N(r)))return{value:r.pow(t.function("Add",[i.op2,t.One])),because:"x^n * x -> x^{n+1}"}}}var U4=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]),CH=new Set(["Sin","Tan","Cot","Csc"]),kH=new Set(["Cos","Sec"]),Z4={Sin:"Cos",Cos:"Sin",Tan:"Cot",Cot:"Tan",Sec:"Csc",Csc:"Sec"},AH={Sin:-1,Cos:-1,Tan:1,Cot:1,Sec:-1,Csc:-1},RH={Sin:1,Cos:-1,Tan:-1,Cot:-1,Sec:-1,Csc:1},PH={Sin:{fn:"Cos",sign:1},Cos:{fn:"Sin",sign:-1},Tan:{fn:"Cot",sign:-1},Cot:{fn:"Tan",sign:-1},Sec:{fn:"Csc",sign:-1},Csc:{fn:"Sec",sign:1}};function DH(e,n){if(C(e)==="Pi"||m(e,"Negate")&&C(e.op1)==="Pi")return null;if(m(e,"Multiply")){let t=e.ops.findIndex(o=>C(o)==="Pi");if(t<0)return null;let i=e.ops.filter((o,s)=>s!==t);if(i.length===0)return null;let r=i.length===1?i[0]:n._fn("Multiply",i);if(r.isInteger===!0&&!N(r))return r}return null}function OH(e){if(!e)return!1;if(m(e,"Divide")&&C(e.op1)==="Pi"&&e.op2?.isSame(2))return!0;if(m(e,"Multiply")&&e.nops===2){let t=(C(e.op1)==="Pi"?e.op2:C(e.op2)==="Pi"?e.op1:void 0)?.re;return typeof t=="number"&&Math.abs(t-.5)<1e-10}return!1}var LH=new Set(["Arcsin","Arccos","Arctan","Arccot","Arcsec","Arccsc"]);function FH(e,n,t){if(!m(n,"Add"))return null;let i=n.ops,r=null,o=-1;for(let c=0;c<i.length;c++){let f=i[c];if(C(f)==="Pi"){r=1,o=c;break}if(m(f,"Multiply")){let p=f.ops,d=p.findIndex(g=>C(g)==="Pi");if(d>=0){let g=p.filter((h,b)=>b!==d);if(g.length===1){let h=g[0];if(N(h)){let b=h.numericValue;if(typeof b=="number"&&Number.isInteger(b)){r=b,o=c;break}}}else if(g.length===0){r=1,o=c;break}}}if(m(f,"Negate")&&C(f.op1)==="Pi"){r=-1,o=c;break}}if(r===null||o<0)return null;let s=e==="Tan"||e==="Cot"?1:2,a=r%s;a<0&&(a+=s);let u=i.filter((c,f)=>f!==o);if(a!==0&&(a===1?u.push(t.Pi):u.push(t.expr(["Multiply",a,"Pi"]))),a===r%s&&a===r)return null;let l;return u.length===0?l=t.Zero:u.length===1?l=u[0]:l=te(...u),t.expr([e,l])}function H4(e){let n=e.operator,t=e.engine;if(U4.has(n)){if(!m(e))return;let i=e.op1;if(!i)return;if(i.isInfinity===!0)return{value:t.NaN,because:`${n}(infinity) -> NaN`};if(m(i,"Negate")){let r=i.op1;if(r){if(CH.has(n))return{value:t._fn(n,[r]).neg(),because:`${n}(-x) -> -${n}(x)`};if(kH.has(n))return{value:t._fn(n,[r]),because:`${n}(-x) -> ${n}(x)`}}}if(m(i,"Subtract")){let r=i.op1,o=i.op2;if(C(r)==="Pi"&&o){let s=RH[n];if(s!==void 0){let a=t._fn(n,[o]);return{value:s===1?a:a.neg(),because:`${n}(\u03C0 - x) -> ${s===1?"":"-"}${n}(x)`}}}}if(m(i,"Add")){let r=i.ops.findIndex(o=>C(o)==="Pi");if(r>=0){let o=i.ops.filter((s,a)=>a!==r);if(o.length===i.ops.length-1){let s=o.length===1?o[0]:t._fn("Add",o),a=AH[n];if(a!==void 0){let u=t._fn(n,[s]);return{value:a===1?u:u.neg(),because:`${n}(\u03C0 + x) -> ${a===1?"":"-"}${n}(x)`}}}}}if(m(i,"Subtract")){let r=i.op1,o=i.op2,s=!1;if(m(r,"Divide")&&C(r.op1)==="Pi"&&r.op2?.isSame(2)&&(s=!0),s&&o){let a=Z4[n];if(a)return{value:t._fn(a,[o]),because:`${n}(\u03C0/2 - x) -> ${a}(x)`}}}if(m(i,"Add")&&i.nops===2){let r=i.ops,o=null,s=null;for(let a of r){if(m(a,"Multiply")&&a.nops===2){let[u,l]=[a.op1,a.op2];if(C(l)==="Pi"){let c=u?.re;typeof c=="number"&&Math.abs(c-.5)<1e-10&&(o=a)}}m(a,"Negate")&&a.op1&&(s=a.op1)}if(o&&s){let a=Z4[n];if(a)return{value:t._fn(a,[s]),because:`${n}(\u03C0/2 - x) -> ${a}(x)`}}}if(m(i,"Add")){let r=i.ops.findIndex(o=>OH(o));if(r>=0){let o=PH[n];if(o){let s=i.ops.filter((a,u)=>u!==r);if(s.length>0){let a=s.length===1?s[0]:t._fn("Add",s),u=t._fn(o.fn,[a]);return{value:o.sign===1?u:u.neg(),because:`${n}(\u03B8 + \u03C0/2) -> ${o.sign===1?"":"-"}${o.fn}(\u03B8)`}}}}}if(n==="Sin"||n==="Cos"){let r=DH(i,t);if(r)return n==="Sin"?{value:t.Zero,because:"Sin(c\xB7\u03C0) -> 0"}:{value:t._fn("Power",[t.NegativeOne,r]),because:"Cos(c\xB7\u03C0) -> (-1)^c"}}if(i.operator==="Add"){let r=FH(n,i,t);if(r)return{value:r,because:`${n} periodicity reduction`}}}if(LH.has(n)){if(!m(e))return;let i=e.op1;if(!i)return;if((n==="Arcsin"||n==="Arccos")&&i.isInfinity===!0)return{value:t.NaN,because:`${n}(infinity) -> NaN`};if(n==="Arctan"){if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.Pi.div(2),because:"arctan(+inf) -> \u03C0/2"};if(i.isInfinity===!0&&i.isNegative===!0)return{value:t.Pi.div(-2),because:"arctan(-inf) -> -\u03C0/2"}}if(n==="Arccot"){if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.Zero,because:"arccot(+inf) -> 0"};if(i.isInfinity===!0&&i.isNegative===!0)return{value:t.Pi,because:"arccot(-inf) -> \u03C0"}}if(n==="Arcsec"&&i.isInfinity===!0)return{value:t.Pi.div(2),because:"arcsec(\xB1inf) -> \u03C0/2"};if(n==="Arccsc"&&i.isInfinity===!0)return{value:t.Zero,because:"arccsc(\xB1inf) -> 0"}}if(n==="Multiply"&&m(e)){if(e.ops.length>=2){let i=null,r=null,o=[];for(let s of e.ops)m(s,"Sin")&&!i?i=s:m(s,"Cos")&&!r?r=s:o.push(s);if(i&&r){let s=i.op1,a=r.op1;if(s?.isSame(a)){let u=t._fn("Sin",[s.mul(2)]);if(o.length===0)return{value:u.div(2),because:"sin(x)*cos(x) -> sin(2x)/2"};{let l=o.length===1?o[0]:t._fn("Multiply",o);return l.isSame(2)?{value:u,because:"2*sin(x)*cos(x) -> sin(2x)"}:{value:l.mul(u).div(2),because:"c*sin(x)*cos(x) -> c*sin(2x)/2"}}}}}if(e.ops.length===2){let[i,r]=e.ops;if(m(i,"Sin")&&m(r)&&r.operator==="Sin"){let o=i.op1,s=r.op1;if(o&&s)return{value:t._fn("Cos",[o.sub(s)]).sub(t._fn("Cos",[o.add(s)])).div(2),because:"sin(x)*sin(y) -> (cos(x-y)-cos(x+y))/2"}}if(m(i,"Cos")&&m(r)&&r.operator==="Cos"){let o=i.op1,s=r.op1;if(o&&s)return{value:t._fn("Cos",[o.sub(s)]).add(t._fn("Cos",[o.add(s)])).div(2),because:"cos(x)*cos(y) -> (cos(x-y)+cos(x+y))/2"}}if(m(i,"Tan")&&m(r)&&r.operator==="Cot"){let o=i.op1,s=r.op1;if(o?.isSame(s))return{value:t.One,because:"tan(x)*cot(x) -> 1"}}if(m(i,"Cot")&&m(r)&&r.operator==="Tan"){let o=i.op1,s=r.op1;if(o?.isSame(s))return{value:t.One,because:"cot(x)*tan(x) -> 1"}}if(i.isSame(2)&&m(r,"Power")&&r.op2?.isSame(2)){let o=r.op1;if(m(o,"Sin")&&o.op1){let s=t._fn("Cos",[o.op1.mul(2)]);return{value:t.One.sub(s),because:"2sin\xB2(x) -> 1 - cos(2x)"}}if(m(o,"Cos")&&o.op1){let s=t._fn("Cos",[o.op1.mul(2)]);return{value:t.One.add(s),because:"2cos\xB2(x) -> 1 + cos(2x)"}}}if(r.isSame(2)&&m(i,"Power")&&i.op2?.isSame(2)){let o=i.op1;if(m(o,"Sin")&&o.op1){let s=t._fn("Cos",[o.op1.mul(2)]);return{value:t.One.sub(s),because:"2sin\xB2(x) -> 1 - cos(2x)"}}if(m(o,"Cos")&&o.op1){let s=t._fn("Cos",[o.op1.mul(2)]);return{value:t.One.add(s),because:"2cos\xB2(x) -> 1 + cos(2x)"}}}}}if(n==="Add"&&m(e)&&e.ops.length>=2){let i=e.ops,r=l=>{if(m(l,"Power")&&l.op2?.isSame(2)){let c=l.op1;if(m(c)&&U4.has(c.operator)&&c.op1)return{fn:c.operator,arg:c.op1}}return null},o=(l,c,f,p)=>{let d=i.filter((g,h)=>h!==l&&h!==c);return d.length===0?{value:f,because:p}:{value:t._fn("Add",[f,...d]),because:p}};for(let l=0;l<i.length;l++){let c=r(i[l]);if(!c||c.fn!=="Sin"&&c.fn!=="Cos")continue;let f=c.fn==="Sin"?"Cos":"Sin";for(let p=0;p<i.length;p++){if(p===l)continue;let d=r(i[p]);if(!(!d||d.fn!==f||!d.arg.isSame(c.arg)))return o(l,p,t.One,"sin\xB2(x) + cos\xB2(x) -> 1")}}let s=l=>{if(!m(l,"Multiply")||l.ops.length!==2)return null;let[c,f]=l.ops,p=(d,g)=>m(d,"Power")&&d.op2?.isSame(2)&&m(d.op1)&&(d.op1.operator==="Sin"||d.op1.operator==="Cos")&&d.op1.op1?{coeff:g,fn:d.op1.operator,arg:d.op1.op1}:null;return p(f,c)??p(c,f)};for(let l=0;l<i.length;l++){let c=s(i[l]);if(!c)continue;let f=c.fn==="Sin"?"Cos":"Sin";for(let p=0;p<i.length;p++){if(p===l)continue;let d=s(i[p]);if(!(!d||d.fn!==f||!d.arg.isSame(c.arg)||!d.coeff.isSame(c.coeff)))return o(l,p,c.coeff,"a*sin\xB2(x) + a*cos\xB2(x) -> a")}}let a=l=>{let c=m(l,"Multiply")?l.ops:[l],f=[];for(let p=0;p<c.length;p++){let d=c[p];if(!m(d,"Power"))continue;let g=d.op1,h=d.op2;if(!m(g)||g.operator!=="Sin"&&g.operator!=="Cos"||!g.op1||h?.isInteger!==!0)continue;let b=h.re;if(typeof b!="number"||b<2)continue;let y=c.filter((E,v)=>v!==p);b===3?y.push(g):b>3&&y.push(t._fn("Power",[g,t.number(b-2)]));let x=y.length===0?t.One:y.length===1?y[0]:t._fn("Multiply",y);f.push({fn:g.operator,arg:g.op1,rest:x})}return f};for(let l=0;l<i.length;l++){let c=a(i[l]);if(c.length!==0)for(let f=0;f<i.length;f++){if(f===l)continue;let p=a(i[f]);if(p.length!==0)for(let d of c){let g=d.fn==="Sin"?"Cos":"Sin";if(p.find(b=>b.fn===g&&b.arg.isSame(d.arg)&&b.rest.isSame(d.rest)))return o(l,f,d.rest,"g*sin\xB2(x) + g*cos\xB2(x) -> g")}}}let u=i.findIndex(l=>l.isSame(1));if(u>=0)for(let l=0;l<i.length;l++){if(l===u)continue;let c=r(i[l]);if(c){if(c.fn==="Tan")return o(l,u,t._fn("Sec",[c.arg]).pow(2),"tan\xB2(x) + 1 -> sec\xB2(x)");if(c.fn==="Cot")return o(l,u,t._fn("Csc",[c.arg]).pow(2),"1 + cot\xB2(x) -> csc\xB2(x)")}}}if(n==="Add"&&m(e)&&e.ops.length===2){let i=s=>{let a=1;for(;m(s,"Negate")&&s.op1;)a=-a,s=s.op1;if(!m(s,"Multiply"))return null;let u,l;for(let c of s.ops){if(N(c)){if(c.isSame(1))continue;if(c.isSame(-1)){a=-a;continue}return null}if(m(c,"Sin")&&c.op1&&u===void 0)u=c.op1;else if(m(c,"Cos")&&c.op1&&l===void 0)l=c.op1;else return null}return u===void 0||l===void 0?null:{sign:a,sinArg:u,cosArg:l}},r=i(e.ops[0]),o=i(e.ops[1]);if(r&&o&&r.sinArg.isSame(o.cosArg)&&r.cosArg.isSame(o.sinArg)){if(r.sign===o.sign){let a=t._fn("Sin",[r.sinArg.add(r.cosArg)]);return{value:r.sign===1?a:a.neg(),because:"sin(x)cos(y)+cos(x)sin(y) -> sin(x+y)"}}let s=r.sign===1?r:o;return{value:t._fn("Sin",[s.sinArg.sub(s.cosArg)]),because:"sin(x)cos(y)-cos(x)sin(y) -> sin(x-y)"}}}if(n==="Add"&&m(e)&&e.ops.length===2){let[i,r]=e.ops,o=null,s=null;if(i.isSame(1)&&m(r,"Negate")?(o=i,s=r.op1):r.isSame(1)&&m(i,"Negate")&&(o=r,s=i.op1),o&&s&&m(s,"Power")&&s.op2?.isSame(2)){let f=s.op1;if(m(f,"Sin"))return{value:t._fn("Cos",[f.op1]).pow(2),because:"1 - sin\xB2(x) -> cos\xB2(x)"};if(m(f,"Cos"))return{value:t._fn("Sin",[f.op1]).pow(2),because:"1 - cos\xB2(x) -> sin\xB2(x)"}}let a=null,u=null;if(i.isSame(-1)&&m(r,"Power")&&r.op2?.isSame(2)?(a=i,u=r):r.isSame(-1)&&m(i,"Power")&&i.op2?.isSame(2)&&(a=r,u=i),a&&m(u)){let f=u.op1;if(m(f,"Sin"))return{value:t._fn("Cos",[f.op1]).pow(2).neg(),because:"sin\xB2(x) - 1 -> -cos\xB2(x)"};if(m(f,"Cos"))return{value:t._fn("Sin",[f.op1]).pow(2).neg(),because:"cos\xB2(x) - 1 -> -sin\xB2(x)"};if(m(f,"Sec"))return{value:t._fn("Tan",[f.op1]).pow(2),because:"sec\xB2(x) - 1 -> tan\xB2(x)"};if(m(f,"Csc"))return{value:t._fn("Cot",[f.op1]).pow(2),because:"csc\xB2(x) - 1 -> cot\xB2(x)"}}let l=null,c=null;if(m(i,"Negate")&&i.op1?.isSame(1)&&m(r)&&r.operator==="Power"&&r.op2?.isSame(2)?(l=i,c=r):m(r,"Negate")&&r.op1?.isSame(1)&&m(i)&&i.operator==="Power"&&i.op2?.isSame(2)&&(l=r,c=i),l&&m(c)){let f=c.op1;if(m(f,"Sec"))return{value:t._fn("Tan",[f.op1]).pow(2),because:"sec\xB2(x) - 1 -> tan\xB2(x)"};if(m(f,"Csc"))return{value:t._fn("Cot",[f.op1]).pow(2),because:"csc\xB2(x) - 1 -> cot\xB2(x)"}}if(m(i,"Negate")&&m(r)&&r.operator==="Negate"){let f=i.op1,p=r.op1;if(m(f,"Power")&&f.op2?.isSame(2)&&m(p)&&p.operator==="Power"&&p.op2?.isSame(2)){let d=f.op1,g=p.op1;if(m(d)&&m(g)&&(d.operator==="Sin"&&g.operator==="Cos"||d.operator==="Cos"&&g.operator==="Sin")&&d.op1?.isSame(g.op1))return{value:t.NegativeOne,because:"-sin\xB2(x) - cos\xB2(x) -> -1"}}}}}var BH=new Set(["Sinh","Cosh","Tanh","Coth","Sech","Csch"]),$H=new Set(["Sinh","Tanh","Coth","Csch"]),qH=new Set(["Cosh","Sech"]),VH=new Set(["Arsinh","Arcosh","Artanh","Arcoth","Arsech","Arcsch"]);function Y4(e){let n=e.operator,t=e.engine;if(BH.has(n)&&m(e)){let i=e.op1;if(!i)return;if(i.isInfinity===!0&&i.isPositive===!0)switch(n){case"Sinh":return{value:t.PositiveInfinity,because:"sinh(+inf) -> +inf"};case"Cosh":return{value:t.PositiveInfinity,because:"cosh(+inf) -> +inf"};case"Tanh":return{value:t.One,because:"tanh(+inf) -> 1"};case"Coth":return{value:t.One,because:"coth(+inf) -> 1"};case"Sech":return{value:t.Zero,because:"sech(+inf) -> 0"};case"Csch":return{value:t.Zero,because:"csch(+inf) -> 0"}}if(i.isInfinity===!0&&i.isNegative===!0)switch(n){case"Sinh":return{value:t.NegativeInfinity,because:"sinh(-inf) -> -inf"};case"Cosh":return{value:t.PositiveInfinity,because:"cosh(-inf) -> +inf"};case"Tanh":return{value:t.NegativeOne,because:"tanh(-inf) -> -1"};case"Coth":return{value:t.NegativeOne,because:"coth(-inf) -> -1"};case"Sech":return{value:t.Zero,because:"sech(-inf) -> 0"};case"Csch":return{value:t.Zero,because:"csch(-inf) -> 0"}}if(m(i,"Negate")){let r=i.op1;if(r){if($H.has(n))return{value:t._fn(n,[r]).neg(),because:`${n}(-x) -> -${n}(x)`};if(qH.has(n))return{value:t._fn(n,[r]),because:`${n}(-x) -> ${n}(x)`}}}}if(VH.has(n)&&m(e)){let i=e.op1;if(!i)return;if(n==="Arsinh"){if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.PositiveInfinity,because:"arsinh(+inf) -> +inf"};if(i.isInfinity===!0&&i.isNegative===!0)return{value:t.NegativeInfinity,because:"arsinh(-inf) -> -inf"}}if(n==="Arcosh"){if(i.isInfinity===!0&&i.isPositive===!0)return{value:t.PositiveInfinity,because:"arcosh(+inf) -> +inf"};if(i.isInfinity===!0&&i.isNegative===!0)return{value:t.NaN,because:"arcosh(-inf) -> NaN"}}if(n==="Artanh"&&i.isInfinity===!0)return{value:t.NaN,because:"artanh(\xB1inf) -> NaN"};if(n==="Arcoth"&&i.isInfinity===!0)return{value:t.Zero,because:"arcoth(\xB1inf) -> 0"};if(n==="Arsech"&&i.isInfinity===!0)return{value:t.NaN,because:"arsech(\xB1inf) -> NaN"};if(n==="Arcsch"&&i.isInfinity===!0)return{value:t.Zero,because:"arcsch(\xB1inf) -> 0"}}}function pu(e){if(N(e))return null;if(m(e,"Add")&&e.nops===2){let[n,t]=[e.op1,e.op2];if(N(t)&&Number.isInteger(t.re)&&!N(n))return{base:n,offset:t.re};if(N(n)&&Number.isInteger(n.re)&&!N(t))return{base:t,offset:n.re}}return{base:e,offset:0}}function W4(e){if(e.operator!=="Binomial"&&e.operator!=="Choose"||!m(e))return;let n=e.op1,t=e.op2;if(!n||!t)return;let i=e.engine;if(t.isSame(0))return{value:i.One,because:"C(n,0) -> 1"};if(t.isSame(1))return{value:n,because:"C(n,1) -> n"};if(t.isSame(n))return{value:i.One,because:"C(n,n) -> 1"};let r=pu(n),o=pu(t);if(r&&o&&r.base.isSame(o.base)&&r.offset-o.offset===1)return{value:n,because:"C(n,n-1) -> n"}}function Q4(e){if(!m(e,"Factorial2"))return;let n=e.op1;if(!n||N(n))return;let t=e.engine,i=pu(n);if(i&&i.offset===1){let o=i.base.div(2);if(o.isInteger===!0&&o.isNonNegative!==!1){let s=t._fn("Multiply",[t._fn("Power",[t.number(2),o]),t._fn("Factorial",[o])]);return{value:t._fn("Divide",[t._fn("Factorial",[n]),s]),because:"(2n+1)!! -> (2n+1)! / (2^n n!)",purpose:"transform"}}}let r=n.div(2);if(r.isInteger===!0&&r.isNonNegative!==!1)return{value:t._fn("Multiply",[t._fn("Power",[t.number(2),r]),t._fn("Factorial",[r])]),because:"(2n)!! -> 2^n n!",purpose:"transform"}}function JH(e){if(m(e,"Factorial"))return{coeff:1,factArg:e.op1};if(m(e,"Negate")&&e.op1.operator==="Factorial"&&m(e.op1))return{coeff:-1,factArg:e.op1.op1};if(m(e,"Multiply")){let n=e.ops,t=-1;for(let s=0;s<n.length;s++)if(m(n[s],"Factorial")){if(t>=0)return null;t=s}if(t<0)return null;let i=n[t];if(!m(i))return null;let r=i.op1,o=n.filter((s,a)=>a!==t);return o.length===1&&N(o[0])&&Number.isInteger(o[0].re)?{coeff:o[0].re,factArg:r}:null}return null}function K4(e){if(!m(e,"Add"))return;let n=e.ops;if(n.length<2)return;let t=[];for(let h=0;h<n.length;h++){let b=JH(n[h]);b&&t.push({...b,index:h})}if(t.length<2)return;let i=e.engine,o=t.map(h=>({...h,bo:pu(h.factArg)})).filter(h=>h.bo!==null);if(o.length<2)return;let s=o[0].bo.base;if(!o.every(h=>h.bo.base.isSame(s)))return;let a=1/0;for(let h of o)h.bo.offset<a&&(a=h.bo.offset);let u=o.find(h=>h.bo.offset===a).factArg,l=[];for(let h of o){let b=h.bo.offset-a;if(b===0)l.push(i.number(h.coeff));else if(b>0&&b<=8){let y=u.add(i.One);for(let x=2;x<=b;x++)y=y.mul(u.add(i.number(x)));h.coeff===1?l.push(y):h.coeff===-1?l.push(y.neg()):l.push(i.number(h.coeff).mul(y))}else return}let c=l.length===1?l[0]:i.function("Add",l),f=i._fn("Factorial",[u]),p=i._fn("Multiply",[f,c]),d=new Set(t.map(h=>h.index)),g=n.filter((h,b)=>!d.has(b));return g.length>0?{value:i._fn("Add",[p,...g]),because:"factor common factorial",purpose:"transform"}:{value:p,because:"factor common factorial",purpose:"transform"}}function X4(e){if(!m(e,"Divide"))return;let n=e.op1,t=e.op2;if(!n||!t)return;let i=e.engine;if(n.isSame(0)&&t.isSame(0))return{value:i.NaN,because:"0/0 -> NaN"};if(n.isSame(0)&&t.isSame(0)===!1&&(N(t)||t.symbols.length!==0))return{value:i.Zero,because:"0/a -> 0"};if(n.isSame(t)&&n.isSame(0)===!1&&n.isInfinity!==!0&&(N(n)||n.symbols.length!==0))return{value:i.One,because:"a/a -> 1"};if(n.isInfinity&&t.isInfinity)return{value:i.NaN,because:"inf/inf -> NaN"};if(m(t,"Divide")){let r=t.op1,o=t.op2;if(!r||!o)return;if(n.isSame(1)&&r.isSame(1)&&o.isSame(0)===!1)return{value:o,because:"1/(1/a) -> a"};if(r.isSame(1)&&o.isSame(0)===!1)return{value:n.mul(o),because:"a/(1/b) -> a*b"};if(o.isSame(0)===!1)return{value:n.mul(o).div(r),because:"a/(b/c) -> a*c/b"}}{let r,o,s,a;if(m(n,"Power")?(r=n.op1,o=n.op2):(r=n,o=i.One),m(t,"Power")?(s=t.op1,a=t.op2):(s=t,a=i.One),r&&s&&r.isSame(s)&&(!Ie(o)||!Ie(a))){let u=i.function("Add",[o,a.neg()]);return u.isSame(0)?{value:i.One,because:"x^a/x^a -> 1"}:u.isSame(1)?{value:r,because:"x^a/x^b -> x when a-b=1"}:{value:i._fn("Power",[r,u]),because:"x^a/x^b -> x^(a-b)"}}}if(n.operator==="Factorial"&&t.operator==="Factorial"&&m(n)&&m(t)){let r=n.op1,o=t.op1;if(N(r)&&N(o)&&r.isInteger&&o.isInteger&&r.isNonNegative&&o.isNonNegative){let u=BigInt(Math.trunc(r.re)),l=BigInt(Math.trunc(o.re));if((u>l?u-l:l-u)>1000n)return;if(u>=l){let f=1n;for(let p=l+1n;p<=u;p++)f*=p;return{value:i.number(f),because:"n!/k! partial product"}}else{let f=1n;for(let p=u+1n;p<=l;p++)f*=p;return{value:i.number([1n,f]),because:"n!/k! -> 1/(partial product)"}}}let s=pu(r),a=pu(o);if(s&&a&&s.base.isSame(a.base)){let u=s.offset-a.offset;if(Number.isInteger(u)&&u>=1&&u<=8){let l=o.add(i.One);for(let c=2;c<=u;c++)l=l.mul(o.add(i.number(c)));return{value:l,because:"n!/k! -> (k+1)..n"}}if(Number.isInteger(u)&&u<=-1&&u>=-8){let l=r.add(i.One);for(let c=2;c<=-u;c++)l=l.mul(r.add(i.number(c)));return{value:i.One.div(l),because:"n!/k! -> 1/((n+1)..k)"}}}}if(m(n,"Factorial")&&t.operator==="Multiply"&&m(t)){let r=n.op1,o=t.ops.filter(a=>m(a,"Factorial")),s=t.ops.filter(a=>!m(a,"Factorial"));if(o.length===2&&s.length===0&&m(o[0])&&m(o[1])){let a=o[0].op1,u=o[1].op1;if(N(r)&&N(a)&&N(u)&&a.re+u.re===r.re){let c=a.re<=u.re?a:u;return{value:i._fn("Binomial",[r,c]),because:"n!/(k!(n-k)!) -> Binomial"}}if(a.add(u).isSame(r))return{value:i._fn("Binomial",[r,a]),because:"n!/(k!(n-k)!) -> Binomial"}}}}var e6=[{match:{sym:"GoldenRatio"},replace:["Divide",["Add",1,["Sqrt",5]],2]},jH,zH,e=>{if(e.operator!=="Divide")return;let n=e.unknowns;if(n.length!==1)return;let t=n[0],i=fl(e,t);if(!i.isSame(e))return{value:i,because:"cancel common polynomial factors"}},e=>{if(!m(e,"Divide"))return;let t=e.op2.operator;if(t!=="Multiply"&&t!=="Power")return;let i=e.unknowns;if(i.length!==1)return;let r=i[0],o=Qa(e,r);if(o.isSame(e))return;let s=e.engine;if(!(s.costFunction(o)>=s.costFunction(e)))return{value:o,because:"partial fraction decomposition"}},e=>{if(!m(e,"Divide"))return;let n=e.op1,t=e.op2;if(!(!n||!t)&&n.isSame(t)&&n.isSame(0)===!1&&n.isInfinity!==!0)return{value:e.engine.One,because:"a/a -> 1"}},e=>{if(!m(e,"Add"))return;let n=e.ops;if(n.length<2)return;let t;for(let o of n){if(!m(o,"Divide"))return;if(t===void 0)t=o.op2;else if(!o.op2.isSame(t))return}let i=Ls(e);if(i.isSame(e))return;let r=e.engine;if(!(r.costFunction(i)>=r.costFunction(e)))return{value:i,because:"combine same-denominator fractions"}},e=>{if(m(e,"Multiply")&&e.ops.some(t=>t.operator==="Factorial")||m(e,"Divide")&&m(e.op2,"Add"))return;if(m(e,"Multiply")){let t=new Map;for(let i of e.ops){let r=null;m(i,"Power")?r=JSON.stringify(i.op1.json):w(i)&&(r=JSON.stringify(i.json)),r&&t.set(r,(t.get(r)||0)+1)}for(let i of t.values())if(i>1)return}let n=Pe(e);return n?{value:n,because:"expand"}:void 0},K4,e=>{if(m(e,"Add"))return{value:te(...e.ops.map(n=>{let t=n.canonical;if(t.unknowns.length===0&&m(t)){let i=t.evaluate();if(N(i))return i}return t})),because:"addition"}},e=>{if(m(e,"Negate"))return{value:e.op1.neg(),because:"negation"}},e=>{if(!m(e,"Multiply"))return;let n=e.ops,t=new Map;for(let i of n){let r=null,o=null;if(m(i,"Power")?(r=JSON.stringify(i.op1.json),o=i):w(i)&&(r=JSON.stringify(i.json),o=i),r&&o){let s=t.get(r)||[];s.push(o),t.set(r,s)}}for(let i of t.values())if(i.length>1)return;if(n.length===2){let[i,r]=n,o=m(i,"Power")&&i.op2.isSame(2)&&["Sin","Cos"].includes(i.op1.operator||"")||m(r,"Power")&&r.op2.isSame(2)&&["Sin","Cos"].includes(r.op1.operator||""),s=N(i)||N(r);if(o&&s)return;let a=i.operator==="Sin"||r.operator==="Sin",u=i.operator==="Cos"||r.operator==="Cos";if(a&&u)return;let l=i.operator==="Tan"||r.operator==="Tan",c=i.operator==="Cot"||r.operator==="Cot";if(l&&c)return}if(!(n.some(i=>i.operator==="Factorial")&&n.some(i=>i.operator==="Add")))return{value:he(...n.map(i=>{let r=i.canonical;if(r.unknowns.length===0&&m(r)){if(r.operator==="Power"&&(C(r.op1)==="ExponentialE"||r.op2.isRational===!0&&r.op2.isInteger===!1))return r;let o=r.evaluate();if(N(o))return o}return r})),because:"multiplication"}},e=>{if(m(e,"Divide")){let n=e.op1,t=e.op2;return!N(t)&&t.symbols.length===0&&(n.isSame(0)||n.isSame(t))||(n.operator==="Ln"||n.operator==="Log")&&(t.operator==="Ln"||t.operator==="Log")||n.operator==="Power"&&t.operator==="Power"&&m(n)&&m(t)&&n.op1.isSame(t.op1)||m(n,"Power")&&n.op1.isSame(t)||m(t,"Power")&&t.op1.isSame(n)||m(t,"Power")&&t.op1.operator==="Divide"||n.operator==="Factorial"&&t.operator==="Factorial"||n.operator==="Factorial"&&t.operator==="Multiply"&&m(t)&&t.ops.some(i=>i.operator==="Factorial")?void 0:{value:n.div(t),because:"division"}}if(m(e,"Rational")&&e.nops===2)return{value:e.op1.div(e.op2),because:"rational"}},e=>{if(!m(e)||!N(e.op1))return;if(e.operator==="Sqrt"){if(e.op1.isNegative)return{value:e.engine.expr(["Multiply",["Sqrt",e.op1.neg()],"ImaginaryUnit"]),because:"sqrt"};let i=e.op1.sqrt();return sS(ze(i))?{value:i,because:"sqrt"}:sS(e.op1.numericValue)?void 0:{value:i,because:"sqrt"}}let n=e.op1,t=e.op2;if(N(t)&&n.isInteger&&t.isInteger&&n.re<Se&&t.re<Se){if(e.operator==="Power")return{value:e.op1.pow(e.op2),because:"power"};if(e.operator==="Root"){let i=e.op1.root(e.op2);if(sS(ze(i)))return{value:e.op1.root(e.op2),because:"root"}}}},e=>{if(e.operator!=="Sign")return;let n=e.sgn,t=e.engine;if(n!==void 0){if(n==="positive")return{value:t.One,because:"sign positive"};if(n==="negative")return{value:t.NegativeOne,because:"sign negative"};if(n==="zero")return{value:t.Zero,because:"sign zero"};if(n==="unsigned")return{value:t.NaN,because:"sign unsinged"}}},e=>{if(m(e)){if(e.operator==="Ln")return e.op1.operator==="Rational"&&e.op1.isInteger===!1?void 0:{value:e.op1.ln(e.ops[1]),because:"ln",purpose:"transform"};if(e.operator==="Log"){let n=e.ops[1]??10,t=typeof n=="number"?e.engine.number(n):n;if(t.isSame(0)||t.isSame(1)||t.isInfinity===!0||e.op1.isSame(0)||e.op1.isInfinity===!0||m(e.op1,"Power")&&e.op1.op1?.isSame(t))return;if(m(e.op1,"Power")&&e.op1.op2){let i=e.op1.op2;if(i.isRational===!1||i.isRational===!0&&i.isInteger===!1||i.isEven===!0)return}if(t.operator==="Rational"){let i=t.json;if(Array.isArray(i)&&i[0]==="Rational"&&i[1]===1)return}if(m(e.op1,"Multiply")){for(let i of e.op1.ops)if(m(i,"Power")&&i.op1?.isSame(t))return}if(m(e.op1,"Divide")){let i=e.op1.op1,r=e.op1.op2;if(i?.operator==="Power"&&m(i)&&i.op1?.isSame(t)||r?.operator==="Power"&&m(r)&&r.op1?.isSame(t))return}return{value:e.op1.ln(n),because:"log"}}}},e=>{if(m(e)){if(e.operator==="Max"){if(e.nops===0)return{value:e.engine.NegativeInfinity,because:"max"};if(e.nops===1)return{value:e.op1,because:"max"}}else if(e.operator==="Min"){if(e.nops===0)return{value:e.engine.PositiveInfinity,because:"min"};if(e.nops===1)return{value:e.op1,because:"min"}}else if(e.operator==="Supremum"){if(e.nops===0)return{value:e.engine.NegativeInfinity,because:"sup"};if(e.nops===1)return{value:e.op1,because:"sup"}}else if(e.operator==="Infimum"){if(e.nops===0)return{value:e.engine.PositiveInfinity,because:"inf"};if(e.nops===1)return{value:e.op1,because:"inf"}}}},e=>{if(!m(e,"Derivative")||e.nops<1||e.nops>2)return;let n=e.engine,[t,i]=e.ops,r=t.simplify();if(!r.isSame(t))return{value:i?n._fn("Derivative",[r,i]):n._fn("Derivative",[r]),because:"derivative"}},e=>m(e,"Hypot")?{value:e.engine.expr(["Sqrt",["Add",["Square",e.op1],["Square",e.op2]]]),because:"hypot(x,y) -> sqrt(x^2+y^2)"}:void 0,e=>{if(!m(e,"Congruent")||e.nops<3)return;let n=e.engine;return{value:n._fn("Equal",[n.function("Mod",[e.ops[0],e.ops[2]]).simplify(),n.function("Mod",[e.ops[1],e.ops[2]]).simplify()]).simplify(),because:"congruent"}},L4,F4,e=>{if(!Q2(e)||!m(e))return;let n=cd(e.operator,e.op1);if(n)return{value:n,because:"constructible value"}},e=>{if(!m(e,"InverseFunction"))return;let n=ld(e.engine,e.ops);if(n)return{value:n,because:"inverse function"}},e=>{if(!m(e,"Arctan2"))return;let[n,t]=e.ops,i=e.engine;if(n.isNaN===!0||t.isNaN===!0)return{value:i.NaN,because:"arctan2"};if(!(N(n)&&n.im!==0||N(t)&&t.im!==0)){if(n.isFinite===!1&&t.isFinite===!1)return{value:i.NaN,because:"arctan2"};if(n.isSame(0)&&t.isSame(0))return{value:i.Zero,because:"arctan2"};if(t.isFinite===!1)return t.isPositive===!0?{value:i.Zero,because:"arctan2"}:t.isNegative===!0?{value:i.Pi,because:"arctan2"}:void 0;if(n.isFinite===!1)return n.isPositive===!0?{value:i.Pi.div(2),because:"arctan2"}:n.isNegative===!0?{value:i.Pi.div(-2),because:"arctan2"}:void 0;if(n.isSame(0))return t.isPositive===!0?{value:i.Zero,because:"arctan2"}:t.isNegative===!0?{value:i.Pi,because:"arctan2"}:void 0;if(t.isSame(0))return n.isPositive===!0?{value:i.Pi.div(2),because:"arctan2"}:n.isNegative===!0?{value:i.Pi.div(-2),because:"arctan2"}:void 0;if(t.isPositive===!0)return{value:i.function("Arctan",[n.div(t)]).evaluate(),because:"arctan2"};if(t.isNegative===!0){let r=i.function("Arctan",[n.div(t)]).evaluate();if(n.isNonNegative===!0)return{value:r.add(i.Pi),because:"arctan2"};if(n.isNegative===!0)return{value:r.sub(i.Pi),because:"arctan2"}}}},O4,$4,q4,V4,J4,j4,oS,H4,Y4,X4,W4,Q4,e=>{if(!m(e,"Multiply")||e.ops.length<2)return;let n=e.engine,t=new Map,i=[];for(let s of e.ops){let a,u;if(m(s,"Power"))a=s.op1,u=s.op2;else if(w(s))a=s,u=n.One;else{i.push(s);continue}let l=JSON.stringify(a.json),c=t.get(l);c||(c={base:a,terms:[]},t.set(l,c)),c.terms.push({term:s,exp:u})}let r=!1;for(let s=i.length-1;s>=0;s--){let a=i[s];if(N(a)){let f=a.numericValue;if(f instanceof Ne&&f.radical>1){let p=f.rational,d=Number(p[0]),g=Number(p[1]),h=new Map,b=hi(f.radical);for(let[E,v]of Object.entries(b)){if(E==="1")continue;let _=Number(E),[I,T]=h.get(_)??[0,1];h.set(_,[I*2+v*T,T*2])}let y=Math.abs(d);if(y>1){let E=hi(y);for(let[v,_]of Object.entries(E)){if(v==="1")continue;let I=Number(v),[T,k]=h.get(I)??[0,1];h.set(I,[T+_*k,k])}}if(g>1){let E=hi(g);for(let[v,_]of Object.entries(E)){if(v==="1")continue;let I=Number(v),[T,k]=h.get(I)??[0,1];h.set(I,[T-_*k,k])}}if(h.size>0&&[...h.keys()].every(E=>t.has(JSON.stringify(n.number(E).json)))){for(let[E,[v,_]]of h){let I=JSON.stringify(n.number(E).json),T=t.get(I),k=Dn(Math.abs(v),_),A=v/k,P=_/k;T.terms.push({term:a,exp:P===1?n.number(A):n.number([A,P])})}i.splice(s,1),d<0&&i.push(n.NegativeOne),r=!0;continue}}}if(!N(a))continue;let u=a.re;if(Number.isInteger(u)&&Math.abs(u)>1){let f=Math.abs(u),p=hi(f),d=Object.keys(p).filter(g=>g!=="1");if(d.length>0&&d.every(g=>t.has(JSON.stringify(n.number(Number(g)).json)))){for(let g of d){let h=p[Number(g)],b=JSON.stringify(n.number(Number(g)).json);t.get(b).terms.push({term:a,exp:n.number(h)})}i.splice(s,1),u<0&&i.push(n.NegativeOne),r=!0;continue}}let l=a.numerator?.re,c=a.denominator?.re;if(l!==void 0&&c!==void 0&&Number.isFinite(l)&&Number.isFinite(c)&&Number.isInteger(l)&&Number.isInteger(c)&&c>1){let f=Math.abs(l),p=f>1?hi(f):{},d=hi(c),g=new Set([...Object.keys(p).filter(h=>h!=="1"),...Object.keys(d).filter(h=>h!=="1")]);if(g.size>0&&[...g].every(h=>t.has(JSON.stringify(n.number(Number(h)).json)))){for(let h of g){let b=Number(h),y=p[b]??0,x=d[b]??0,E=JSON.stringify(n.number(b).json);t.get(E).terms.push({term:a,exp:n.number(y-x)})}i.splice(s,1),l<0&&i.push(n.NegativeOne),r=!0}}}for(let s of t.values())if(s.terms.length>1){let a=s.base;if(a.isPositive===!0||a.isNegative===!0||N(a))r=!0;else{let l=s.terms.map(f=>f.exp);if(n.function("Add",l).isPositive===!0)r=!0;else{for(let f of s.terms)i.push(f.term);s.terms.length=0}}}if(!r)return;let o=[...i];for(let s of t.values())if(s.terms.length===1)o.push(s.terms[0].term);else{let a=s.terms.map(l=>l.exp),u=n.function("Add",a);u.isSame(0)?o.push(n.One):u.isSame(1)?o.push(s.base):o.push(n._fn("Power",[s.base,u]))}return o.length===0?{value:n.One,because:"combined powers",purpose:"transform"}:o.length===1?{value:o[0],because:"combined powers",purpose:"transform"}:{value:n._fn("Multiply",o),because:"combined powers with same base",purpose:"transform"}}];function sS(e){return e===void 0?!1:typeof e=="number"?Number.isInteger(e):e.isExact}function jH(e){let n=e.operator;if(!rr(n)&&!wa(n))return;let t=e,i=e.engine;if(!m(e))return;let r=e.op1.simplify(),o=e.op2.simplify();if(e=i._fn(e.operator,[r,o]),e=Wa(e)??e,mt(e.operator),m(e)&&e.nops===2&&!e.op2.isSame(0)){let s=Wa(i._fn(e.operator,[e.op1.sub(e.op2),i.Zero]));i.costFunction(s)<i.costFunction(e)&&(e=s)}if(!e.isSame(t))return{value:e,because:"simplify-relational-operator"}}function zH(e){if(!m(e,"List")||!e.ops.every(i=>wa(i.operator)||rr(i.operator)))return;let n=e.engine,t=e.ops.map(i=>i.simplify());if(!t.every((i,r)=>i.isSame(e.ops[r])))return{value:n.function("List",t),because:"simplify-system-of-equations"}}function r6(e,n){return ba(n,e.context.lexicalScope)}function GH(e){if(fe(e)){let n=e.operator;return n.evaluate||n.collection?"function":"opaque"}if(ie(e))return e.value.isConstant?"constant":"variable"}function UH(e){let n=fe(e)?e.operator.description:ie(e)?e.value.description:void 0;return n?typeof n=="string"?[n]:n:[]}function ZH(e){return(fe(e)?e.operator.keywords:ie(e)?e.value.keywords:void 0)??[]}function o6(e,n,t){let i=(typeof n=="string"?[n]:n).map(p=>p.trim().toLowerCase().replace(/\s+/g," ")).filter(p=>p.length>0);if(i.length===0)return[];let r=[...new Set(i.flatMap(p=>p.split(" ")))],o=[...new Set([...r,...i.filter(p=>p.includes(" "))])],s=t?.limit??10;Number.isFinite(s)||(s=10),s=Math.max(1,Math.min(100,Math.floor(s)));let a=new Map,u=e.latexSyntax?.getNamedTriggers?.();if(u)for(let{name:p,triggers:d}of u)a.set(p,d);let l=[],c=new Set,f=e.context.lexicalScope;for(;f;){for(let[p,d]of f.bindings){if(c.has(p))continue;c.add(p);let g=GH(d);if(g===void 0)continue;let h=p.toLowerCase(),b=(a.get(p)??[]).map(T=>T.toLowerCase()),y=UH(d).map(T=>T.toLowerCase()),x=ZH(d).map(T=>T.toLowerCase()),E=[h,...b,...x,...y],v=T=>{if(h===T)return 0;if(h.startsWith(T))return 1;if(b.some(k=>k===T)||x.some(k=>k===T))return 2;if(h.includes(T))return 3;if(b.some(k=>k.includes(T)))return 4;if(E.some(k=>k.includes(T)))return 5},_=r.filter(T=>v(T)!==void 0).length;if(_===0)continue;let I=1/0;for(let T of o){let k=v(T);k!==void 0&&k<I&&(I=k)}l.push({id:p,kind:g,matched:_,tier:I})}f=f.parent}return l.sort((p,d)=>p.matched!==d.matched?d.matched-p.matched:p.tier!==d.tier?p.tier-d.tier:p.id.length!==d.id.length?p.id.length-d.id.length:p.id<d.id?-1:p.id>d.id?1:0),l.slice(0,s).map(({id:p,kind:d})=>({id:p,kind:d}))}var n6=new WeakMap;function HH(e){let n=n6.get(e);if(n&&n.generation===e._generation)return n.names;let t=[],i=new Set,r=e.context.lexicalScope;for(;r;){for(let[o,s]of r.bindings)i.has(o)||(i.add(o),fe(s)&&t.push(o));r=r.parent}return n6.set(e,{generation:e._generation,names:t}),t}function s6(e,n){if(!n)return;let t=HH(e),i=n.toLowerCase(),r=u=>{let l=u.toLowerCase(),c=0;for(;c<i.length&&c<l.length&&i[c]===l[c];)c+=1;return c},o=u=>{if(u.length!==0)return u.sort((l,c)=>{let f=r(l),p=r(c);return f!==p?p-f:l.length!==c.length?l.length-c.length:l<c?-1:l>c?1:0})[0]},s=t.filter(u=>u!==n&&u.toLowerCase()===i);if(s.length>0)return o(s);let a=[];for(let u of t){let l=u.toLowerCase();(l===`${i}s`||i.endsWith("s")&&l===i.slice(0,-1))&&a.push(u)}if(a.length>0)return o(a);if(n.length>=5){let u=n.length>=6?2:1,l=u+1,c=[];for(let f of t){if(f===n)continue;let p=A1(i,f.toLowerCase(),u);p>u||(p<l?(l=p,c=[f]):p===l&&c.push(f))}if(c.length>0)return o(c)}if(n.length>=3){let u=t.filter(l=>l!==n&&l.toLowerCase().startsWith(i));if(u.length===1)return u[0]}}function a6(e,n,t,i){i??=e.context.lexicalScope,i.bindings.set(n,{value:new ur(e,n,{type:"unknown",inferred:!0})});let r=i.bindings.get(n);return Si(e,n,r,t),e._generation+=1,r}function u6(e,n,t,i){i??=e.context.lexicalScope,i.bindings.set(n,{value:new ur(e,n,{type:"function"})});let r=i.bindings.get(n);return Si(e,n,r,t),e._generation+=1,r}function l6(e,n){let t=ba(n,e.context.lexicalScope);if(!(!t||!ie(t)))return t.value.value}function c6(e,n,t){typeof t=="number"?t=e.number(t):typeof t=="boolean"&&(t=t?e.True:e.False);let i=ba(n,e.context.lexicalScope);if(!i)throw new Error(`Unknown symbol "${n}"`);if(ie(i)){i.value.value=t,e._generation+=1;return}throw new Error(`Cannot assign a value to operator symbol "${n}"`)}function f6(e,n,t,{alias:i}={}){if(!bw(n))throw Error(`The type name "${n}" is invalid`);let r=e.context.lexicalScope;if(r.types?.[n])throw Error(`The type "${n}" is already defined in the current scope`);r.types??={},i??=!1,r.types[n]={kind:"reference",name:n,alias:i,def:void 0};let o=t instanceof Z?t.type:typeof t=="string"?Y(t,e._typeResolver):t;r.types[n].def=o}function p6(e,n,t,i){if(typeof n!="string"){for(let[u,l]of Object.entries(n))e.declare(u,l);return e}let r=n;if(r==="Nothing")return e;if(t==null)throw Error(`Expected a definition or type for "${r}"`);if(typeof r!="string"||r.length===0||!yn(r))throw new Error(`Invalid symbol "${r}": ${vi(r)}`);i??=e.context.lexicalScope;let s=i.bindings.get(r);if(s!==void 0&&!(ie(s)&&s.value.inferredType&&s.value.value===void 0||fe(s)&&s.operator.inferredSignature))throw new Error(`The symbol "${r}" is already declared in this scope`);let a=t;if(Rf(a)){let u=a;if(a.type!==void 0&&m(a.value,"Function")){let l=a.type instanceof Z?a.type.type:Y(a.type);Iu(l)!==void 0&&(aS(r,a.value,l,e.type(l).toString()),u={...a,value:uS(e,a.value,l)})}return e._declareSymbolValue(r,u,i),e}if(Af(a))return e._declareSymbolOperator(r,a,i),e;{let u=Y(a,e._typeResolver);if(!No(u))throw Error([`Invalid argument for "${r}"`,JSON.stringify(a,void 0,4),"Use a type, a `OperatorDefinition` or a `ValueDefinition`"].join(`
|
|
134
134
|
| `));e._declareSymbolValue(r,{type:u},i)}return e}function d6(e,n,t){if(typeof n=="object"){for(let[a,u]of Object.entries(n))e.assign(a,u);return e}let i=n;if(i==="Nothing")return e;let r=e.lookupDefinition(i);if(ie(r)&&!r.value.isConstant&&!r.value.inferredType&&t!==void 0&&t!==null&&typeof t!="function"&&Iu(r.value.type.type)!==void 0){let a=Ve(e.expr(t));if(a!==void 0){let u=r.value.type;aS(i,a,u.type,u.toString());let l=uS(e,a,u.type);if(!l.type.matches(u))throw new Error([`Symbol "${i}"`,`The value "${l.toString()}" of type "${l.type}" is not compatible with the type "${u}"`].join(`
|
|
@@ -137,12 +137,12 @@ Error in definition of "${i}"`,"",JSON.stringify(r,void 0,4),"",o instanceof Err
|
|
|
137
137
|
| `))}function uS(e,n,t){if(!m(n,"Function"))return n;let i=bn(t);if(i===void 0||Uc(n)!==void 0)return n;let r=bn(n.type.type);if(r!==void 0&&e.type(r).matches(e.type(i)))return n;let o=e.box(["Function",["Typed",n.ops[0].json,`'${e.type(i).toString()}'`],...n.ops.slice(1).map(s=>s.json)]);return m(o,"Function")?o:n}var ia="\x1B[0m";var cS="\x1B[30;1m";var fS="\x1B[34;1m";var pS="\x1B[36;1m";var Ob="\x1B[1m";var lS={black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,white:7,grey:8,gray:8,"bright-red":9,"bright-green":10,"bright-yellow":11,"bright-blue":12,"bright-magenta":13,"bright-cyan":14,"bright-white":15},WH={black:"#2E3436",red:"#ff0000",green:"#4E9A06",yellow:"#C4A000",blue:"#3465A4",magenta:"#75507B",cyan:"#06989A",white:"#D3D7CF",grey:"#555753",gray:"#555753","bright-red":"#EF2929","bright-green":"#8AE234","bright-yellow":"#FCE94F","bright-blue":"#729FCF","bright-magenta":"#AD7FA8","bright-cyan":"#34E2E2","bright-white":"#EEEEEC"};function m6(e){let n=WH[e];if(n===void 0)return[];let t=[],i=n.match(/#([\da-f]{2})([\da-f]{2})([\da-f]{2})/i);return i!==null?t=i.slice(1).map(r=>parseInt(r,16)):(i=n.match(/#([\da-f])([\da-f])([\da-f])/i),t=i.slice(1).map(r=>16*parseInt(r,16))),t}function g6(e,n){if(n==="none")return[];if(e==="default")return[39];if(n==="basic"){let t=typeof e=="string"?lS[e]:e;return t===void 0?[]:t<8?[30+t]:[90+t-8]}return typeof e=="number"&&(e=Object.keys(lS)[e]),[38,2,...m6(e)]}function h6(e,n){if(n==="none")return[];if(e==="default")return[49];if(n==="basic"){let t=lS[e];return t===void 0?[]:t<8?[40+t]:[100+t-8]}return[48,2,...m6(e)]}var md=class e{_items;constructor(n){n?n instanceof e?this._items=new Map(n._items):this._items=new Map(n):this._items=new Map}has(n){for(let t of this._items.keys())if(t.isSame(n))return!0;return!1}get(n){for(let[t,i]of this._items)if(t.isSame(n))return i}clear(){this._items.clear()}set(n,t){for(let i of this._items.keys())if(i.isSame(n)){this._items.set(i,t);return}this._items.set(n,t)}delete(n){for(let t of this._items.keys())if(t.isSame(n)){this._items.delete(t);return}this._items.delete(n)}[Symbol.iterator](){return this._items.entries()}entries(){return this._items.entries()}};function b6(e,n,t){dS(e,n??{parent:e.context?.lexicalScope,bindings:new Map},t)}function y6(e){mS(e)}function dS(e,n,t){if(!t){let i=e._evalContextStack.length;i===0&&(t="system"),i===1&&(t="global"),t??=`anonymous_${i-1}`}e._evalContextStack.push({lexicalScope:n,name:t,assumptions:new md(e.context?.assumptions??[])})}function mS(e){let n=e._evalContextStack.pop();for(let t of n?.lexicalScope.bindings.values()??[])ie(t)&&t.value.dispose();e._generation+=1,n?._assumptionsDirty&&(e._mutationGeneration+=1)}function x6(e,n,t){if(!n)return t();e._evalContextStack.push({lexicalScope:n,name:"",assumptions:new md(e.context?.assumptions??[])});try{return t()}finally{e._evalContextStack.pop()?._assumptionsDirty&&(e._mutationGeneration+=1)}}function E6(e,n){n?(n={...n},n.maxDepth??=1,n.details??=!1):n={details:!1,maxDepth:-2},n.maxDepth!==void 0&&n.maxDepth<0&&(n.maxDepth=e._evalContextStack.length+n.maxDepth),n.maxDepth=Math.min(e._evalContextStack.length-1,n.maxDepth);let t=0;for(;t<=n.maxDepth;){let i=e._evalContextStack[e._evalContextStack.length-1-t];t===0?console.group(`${Ob}${fS}${i.name}${ia}`):console.groupCollapsed(`${Ob}${fS}${i.name}${ia} ${cS}(${t})${ia}`);let r=[...i.assumptions.entries()].map(([o,s])=>`${o}: ${s}`);if(r.length>0){console.groupCollapsed(`${Ob}${r.length} assumptions${ia}`);for(let o of r)console.info(o);console.groupEnd()}if(i.lexicalScope.bindings.size===0){console.groupEnd(),t+=1;continue}for(let[o,s]of i.lexicalScope.bindings)console.info(QH(o,s));console.groupEnd(),t+=1}}function QH(e,n){let t="";if(ie(n)){let i=[];n.value.holdUntil==="never"&&i.push("(hold never)"),n.value.holdUntil==="N"&&i.push("(hold until N)"),n.value.inferredType&&i.push("inferred");let r=i.length>0?` ${i.join(" ")}`:"";t=`${pS}${e}${ia}:${r}`,n.value.isConstant?(t+=` const ${n.value.type.toString()}`,n.value.value!==void 0&&(t+=` = ${n.value.value?.toString()}`)):t+=` ${n.value.type.toString()}`}else if(fe(n)){let i=[];n.operator.inferredSignature&&i.push("(inferred)");let r=i.length>0?` (${i.join(" ")})`:"";t=`${pS}${e}${ia}:${r} ${n.operator.signature.toString()}`;let o=[];n.operator.lazy&&o.push("lazy"),n.operator.scoped&&o.push("scoped"),n.operator.broadcastable&&o.push("broadcastable"),n.operator.associative&&o.push("associative"),n.operator.commutative&&o.push("commutative"),n.operator.idempotent&&o.push("idempotent"),n.operator.involution&&o.push("involution"),n.operator.pure||o.push("not pure");let s=o.map(a=>`${cS}${a}${ia}`).join(" ");s.length>0&&(t+=`
|
|
138
138
|
\u2514 ${s}`)}else t="unknown";return t}function v6(e,n){return n.type.matches("integer")?e.type("integer"):n.type.matches("rational")||n.type.matches("real")?e.type("real"):n.type.matches("complex")?e.type("number"):n.type}function gS(e){let n=e.operator;if(n==="Element")return rY(e);if(n==="NotElement")return tY(e);if(n==="Equal")return iY(e);if(n==="NotEqual")return nY(e);if(n==="And")return eY(e);if(rr(n))return yS(e);if(XH.has(n))return"not-a-predicate";throw new Error("Unsupported assumption. Use `Element`, `NotElement`, `Equal`, `NotEqual`, `And` or an inequality")}var KH={PositiveNumbers:{type:"real",op:"Greater",value:0},NonNegativeNumbers:{type:"real",op:"GreaterEqual",value:0},NegativeNumbers:{type:"real",op:"Less",value:0},NonPositiveNumbers:{type:"real",op:"LessEqual",value:0},PositiveIntegers:{type:"integer",op:"GreaterEqual",value:1},NonNegativeIntegers:{type:"integer",op:"GreaterEqual",value:0},NegativeIntegers:{type:"integer",op:"LessEqual",value:-1},NonPositiveIntegers:{type:"integer",op:"LessEqual",value:0}},XH=new Set(["Or","Not","Implies","Equivalent","Xor","Nand","Nor","ForAll","Exists","ExistsUnique","ForElement"]);function eY(e){if(e.operator,!m(e))return"not-a-predicate";let n=e.engine;n.pushScope();let t;try{t=S6(e)}finally{n.popScope()}return t==="contradiction"||t==="internal-error"?t:S6(e)}function S6(e){if(!m(e))return"not-a-predicate";let n=!1,t=!1;for(let i of e.ops){let r=gS(i);if(r==="contradiction"||r==="internal-error")return r;r==="not-a-predicate"?t=!0:r==="ok"&&(n=!0)}return t?"not-a-predicate":n?"ok":"tautology"}function nY(e){return e.operator,!m(e)||e.ops.length!==2?"not-a-predicate":hS(e.engine,e.op1,e.op2)}function hS(e,n,t){let i=e.function("NotEqual",[n,t]);if(!i.isValid)return"not-a-predicate";if(i.unknowns.length===0){let r=i.evaluate();if(w(r,"True"))return"tautology";if(w(r,"False"))return"contradiction"}return e.context.assumptions.set(i,!0),"ok"}function tY(e){if(e.operator,!m(e)||e.ops.length!==2)return"not-a-predicate";let n=e.engine,t=e.op2.evaluate();return t.isValid?bS(n,e.op1,t):"not-a-predicate"}function bS(e,n,t){let i=e.function("NotElement",[n,t]);if(!i.isValid)return"not-a-predicate";let r=w(n)?n.symbol:void 0;if(r===void 0||I6(e,r)){let o=i.evaluate();if(w(o,"True"))return"tautology";if(w(o,"False"))return"contradiction"}return e.context.assumptions.set(i,!0),"ok"}function iY(e){e.operator;let n=e.unknowns;if(n.length===0){let o=e.evaluate();return w(o,"True")?"tautology":w(o,"False")?"contradiction":"not-a-predicate"}let t=e.engine;if(!m(e))return"not-a-predicate";let i=e.op1,r=w(i)?i.symbol:void 0;if(r&&!I6(t,r)&&!e.op2.has(r)){let o=e.op2.evaluate();if(!o.isValid)return"not-a-predicate";let s=t.lookupDefinition(r);return!s||!ie(s)?(t.declare(r,{value:o}),Lb(t,r),"ok"):s.value.type&&!o.type.matches(s.value.type)&&!s.value.inferredType?"contradiction":(Lb(t,r),t.context.lexicalScope.bindings.has(r)?(s.value.inferredType&&(s.value.type=v6(t,o)),t._setSymbolValue(r,o)):t.declare(r,{value:o}),"ok")}if(n.length===1){let o=n[0],s=rn(e,o),a=t.lookupDefinition(o);if(a&&ie(a)&&a.value.type&&!a.value.inferredType&&s.length>0&&!s.some(l=>!l.type||l.type.matches(a.value.type)))return"contradiction";if(s.length!==1)return t.context.assumptions.set(t.function("Equal",[e.op1.sub(e.op2),0]),!0),"ok";let u=s[0];return!a||!ie(a)?(t.declare(o,{value:u}),Lb(t,o),"ok"):(Lb(t,o),t.context.lexicalScope.bindings.has(o)?(a.value.inferredType&&(a.value.type=v6(t,u)),t._setSymbolValue(o,u)):t.declare(o,{value:u}),"ok")}return t.context.assumptions.set(e,!0),"ok"}function yS(e){let n=e.engine;if(!m(e))return"internal-error";if(e.ops.length>2){let c=e.ops,f=e.operator,p=!1;for(let d=0;d+1<c.length;d++){let g=yS(n.function(f,[c[d],c[d+1]]));if(g==="contradiction"||g==="internal-error")return g;g==="ok"&&(p=!0)}return p?"ok":"tautology"}let t="",i,r;if(e.operator==="Less"?(i=e.op1,r=e.op2,t="<"):e.operator==="LessEqual"?(i=e.op1,r=e.op2,t="<="):e.operator==="Greater"?(i=e.op2,r=e.op1,t="<"):e.operator==="GreaterEqual"&&(i=e.op2,r=e.op1,t="<="),!t)return"internal-error";let o=i.canonical.sub(r.canonical),s=n.expr([t==="<"?"Less":"LessEqual",o,0]).evaluate();if(w(s,"True"))return"tautology";if(w(s,"False"))return"contradiction";let a=s.unknowns;if(a.length===0)return"not-a-predicate";let u=m(s)?s.op1:void 0,l=u!==void 0?oY(u):void 0;if(l!==void 0){let c=ay(s,l);if(c!==void 0){let p=rt(n,l),d=sY(p,c);if(d!==void 0)return d}let f=l.part==="abs"&&c!==void 0&&ls(c.upper)!==void 0?"finite_number":"number";return uY(n,l.symbol,f),n.context.assumptions.set(s,!0),l.part==="im"&&c!==void 0&&aY(c)&&(bS(n,n.symbol(l.symbol),n.symbol("RealNumbers")),hS(n,n.symbol(l.symbol),n.Zero)),"ok"}if(a.length===1){let c=a[0],f=rt(n,c),p=e.operator,d=e.op1,g=e.op2,h=w(d,c),b=h?g:d,y=N(b)?b.numericValue:void 0;if(y!==void 0){let x=y;if(typeof x=="number"&&isFinite(x)){let E;if(p==="Greater"?E=h?"greater":"less":p==="GreaterEqual"?E=h?"greaterEqual":"lessEqual":p==="Less"?E=h?"less":"greater":E=h?"lessEqual":"greaterEqual",E==="greater"||E==="greaterEqual"){let v=E==="greater";if(f.lower!==void 0){let _=N(f.lower)?f.lower.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(v){if(_>x||f.lowerStrict&&_>=x)return"tautology"}else if(_>x||f.lowerStrict&&_>=x||!f.lowerStrict&&_>=x)return"tautology"}}if(f.upper!==void 0){let _=N(f.upper)?f.upper.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(v){if(_<x||f.upperStrict&&_<=x||!f.upperStrict&&_<=x)return"contradiction"}else if(_<x||f.upperStrict&&_<=x)return"contradiction"}}}else{let v=E==="less";if(f.upper!==void 0){let _=N(f.upper)?f.upper.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(v){if(_<x||f.upperStrict&&_<=x)return"tautology"}else if(_<x||_<=x)return"tautology"}}if(f.lower!==void 0){let _=N(f.lower)?f.lower.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(v){if(_>x||f.lowerStrict&&_>=x||!f.lowerStrict&&_>=x)return"contradiction"}else if(_>x||f.lowerStrict&&_>x)return"contradiction"}}}}}}if(a.length===1&&(u===void 0||!N6(u))){let c=a[0],f=n.lookupDefinition(c);f?ie(f)&&f.value.inferredType&&(n.context?.lexicalScope?.bindings.has(c)?f.value.type=n.type("real"):n.declare(c,{type:"real"})):n.declare(c,{type:"real"})}return s.operator==="Less"||s.operator,n.context.assumptions.set(s,!0),"ok"}function rY(e){e.operator;let n=e.engine;if(!m(e))return"not-a-predicate";let t=e.op2.evaluate();if(!t.isValid)return"not-a-predicate";let i=e.op1;if(w(i))return _6(n,i.symbol,t);let r=lY(i);if(r.length===1){let s=Cf(t);if(s!=="unknown")return n.declare(r[0],s),"ok"}if(r.length>0)return n.context.assumptions.set(e,!0),"ok";let o=e.evaluate();return w(o,"True")?"tautology":w(o,"False")?"contradiction":"not-a-predicate"}function _6(e,n,t){let i=Cf(t);if(i!=="unknown")return mc(e,n,i);if(w(t)){let o=KH[t.symbol];if(o!==void 0)return mc(e,n,o.type)==="contradiction"||gd(e,n,o.op,e.number(o.value))==="contradiction"?"contradiction":"ok"}if(m(t,"Range")&&t.ops.length>=2){let o=mc(e,n,"integer");if(o==="contradiction")return o;let[s,a]=t.ops,u=t.ops[2];return u!==void 0&&u.isSame(-1)&&([s,a]=[a,s]),u!==void 0&&!u.isSame(1)&&!u.isSame(-1)?"ok":gd(e,n,"GreaterEqual",s)==="contradiction"||gd(e,n,"LessEqual",a)==="contradiction"?"contradiction":"ok"}if(m(t,"Interval")&&t.ops.length===2){let o=mc(e,n,"real");if(o==="contradiction")return o;let[s,a]=t.ops,u=!1,l=!1;return m(s,"Open")&&(u=!0,s=s.op1),m(a,"Open")&&(l=!0,a=a.op1),gd(e,n,u?"Greater":"GreaterEqual",s)==="contradiction"||gd(e,n,l?"Less":"LessEqual",a)==="contradiction"?"contradiction":"ok"}if(m(t,"SetMinus")&&t.ops.length===2){let[o,s]=t.ops,a=_6(e,n,o.evaluate());if(a==="contradiction"||a==="internal-error")return a;if(m(s,"Set")){for(let l of s.ops)if(hS(e,e.symbol(n),l)==="contradiction")return"contradiction";return"ok"}let u=bS(e,e.symbol(n),s);return u==="tautology"?"ok":u}if(m(t,"Union")&&t.ops.length>0){if(t.ops.every(o=>m(o,"Range"))){if(mc(e,n,"integer")==="contradiction")return"contradiction"}else if(t.ops.every(o=>m(o,"Interval")||m(o,"Range"))&&mc(e,n,"real")==="contradiction")return"contradiction"}if(N(t)||q(t))return"not-a-predicate";let r=e.function("Element",[e.symbol(n),t]);return r.isValid?(e.context.assumptions.set(r,!0),"ok"):"not-a-predicate"}function mc(e,n,t){if(!w6(e,n))return e.declare(n,t),"ok";e.context?.lexicalScope?.bindings.has(n)||e.declare(n,t);let i=e.lookupDefinition(n);if(ie(i)){if(i.value.type&&!i.value.type.isUnknown&&!i.value.inferredType){let r=Bn({kind:"intersection",types:[t,i.value.type.type]});return r==="nothing"?"contradiction":(i.value.type=new Z(r,e._typeResolver),i.value.inferredType=!1,"ok")}return i.value.type=new Z(t,e._typeResolver),i.value.inferredType=!1,"ok"}return fe(i)?$(t,bn(i.operator.signature.type))?"ok":"contradiction":"not-a-predicate"}function gd(e,n,t,i){return!N(i)||i.isFinite!==!0?"ok":yS(e.function(t,[e.symbol(n),i]))}function oY(e){let n=r=>{let o=m(r,"Negate")&&r.ops.length===1?r.op1:r,s=Ft(o);return s!==void 0&&s.part!=="self"?s:void 0},t=n(e);if(t!==void 0)return t;if(!m(e,"Add"))return;let i;for(let r of e.ops){let o=n(r);if(o!==void 0){if(i!==void 0)return;i=o}else if(!N(r))return}return i}function N6(e){if(!m(e))return!1;let n=Ft(e);return n!==void 0&&n.part!=="self"?!0:e.ops.some(N6)}function ls(e){if(e===void 0||!N(e))return;let n=e.numericValue,t=typeof n=="number"?n:n?.re;return typeof t=="number"&&isFinite(t)?t:void 0}function sY(e,n){let t=ls(n.lower);if(t!==void 0){let r=n.lowerStrict===!0,o=ls(e.upper);if(o!==void 0&&(o<t||o===t&&(r||e.upperStrict===!0)))return"contradiction";let s=ls(e.lower);if(s!==void 0&&(s>t||s===t&&(e.lowerStrict===!0||!r)))return"tautology"}let i=ls(n.upper);if(i!==void 0){let r=n.upperStrict===!0,o=ls(e.lower);if(o!==void 0&&(o>i||o===i&&(r||e.lowerStrict===!0)))return"contradiction";let s=ls(e.upper);if(s!==void 0&&(s<i||s===i&&(e.upperStrict===!0||!r)))return"tautology"}}function aY(e){let n=ls(e.lower);if(n!==void 0&&(n>0||n===0&&e.lowerStrict===!0))return!0;let t=ls(e.upper);return t!==void 0&&(t<0||t===0&&e.upperStrict===!0)}function uY(e,n,t){let i=e.lookupDefinition(n);if(!i){e.declare(n,t);return}if(!ie(i)||i.value.isConstant)return;let r=i.value.type;if(!r||r.isUnknown||i.value.inferredType&&$(t,r.type)){if(!e.context?.lexicalScope?.bindings.has(n)){e.declare(n,t);return}i.value.type=e.type(t)}}function w6(e,n){return e.lookupDefinition(n)!==void 0}function lY(e){return e.symbols.filter(n=>!w6(e.engine,n))}function Lb(e,n){(e.context.assumptionBindings??=new Set).add(n)}function I6(e,n){let t=e.lookupDefinition(n);return t?!!(ie(t)&&t.value.isConstant||e._getSymbolValue(n)!==void 0):!1}function T6(e,n){if(!Xi(e))return;let t=Hd(n),i=_r(e),r=Io(t),o=i.bySubject.get(r);if(o!==void 0){let s=Yd(o.bounds);if((s==="non-negative"||s==="non-positive")&&o.notEqual.some(a=>a.isSame(0))&&(s=s==="non-negative"?"positive":"negative"),s!==void 0)return s}if(i.inequalitySubjects.has(r))return cY(e,t)}function cY(e,n){let t=e.context?.assumptions;if(t)for(let[i,r]of t.entries()){let o=i.operator;if(!o||o!=="Less"&&o!=="LessEqual"||!m(i))continue;let s=i.ops;if(s.length!==2)continue;let[a,u]=s;if(u.isSame(0)){if(Ki(a,n)){if(o==="Less")return"negative";if(o==="LessEqual")return"non-positive"}if(m(a,"Negate")&&Ki(a.op1,n)){if(o==="Less")return"positive";if(o==="LessEqual")return"non-negative"}if(m(a,"Subtract")){let[l,c]=a.ops;if(l&&c){if(Ki(c,n)&&l.isNonNegative===!0&&o==="Less")return"positive";if(Ki(l,n)&&c.isNonPositive===!0&&o==="Less")return"negative"}}if(m(a,"Add"))for(let l of a.ops){if(Ki(l,n)){let c=a.ops.filter(f=>f!==l);if(c.length>0&&c.every(f=>f.isNonNegative===!0)){if(o==="Less")return"negative";if(o==="LessEqual")return"non-positive"}}if(m(l,"Negate")&&Ki(l.op1,n)){let c=a.ops.filter(f=>f!==l);if(c.length>0&&c.every(f=>f.isNonNegative===!0)){if(o==="Less")return"positive";if(o==="LessEqual")return"non-negative"}}}}}}function M6(e,n,t){if(typeof n!="string")return e.expr(n,{form:"raw"});let i=ys(n)??n,r=ar(i),o=r===null?null:e.expr(r);if(o===null||!o.isValid)throw new Error(`${t}(): cannot parse the predicate string ${JSON.stringify(n)} as a mathematical expression`);return o}function xS(e,n){let t=e.expr(n,{form:"raw"}),i=[],r=c=>c.operator.startsWith("_")||We(c)?!0:m(c)?c.ops.some(r):!1,o=c=>{let f=Object.keys(c).sort();for(let p of i){let d=Object.keys(p).sort();if(d.length!==f.length)continue;let g=!0;for(let h=0;h<f.length;h++){if(d[h]!==f[h]){g=!1;break}let b=f[h];if(!c[b].isSame(p[b])){g=!1;break}}if(g)return}i.push(c)},s=e.context.assumptions,a=()=>{let c=new Set;for(let[f,p]of s)if(p===!0)for(let d of f.symbols)c.add(d);return[...c]},u=c=>{let f=c.operator;if(f==="Equal"){if(!m(c)||c.ops.length!==2)return[{pattern:c}];let b=c.op1.canonical.sub(c.op2.canonical);return[{pattern:c},{pattern:e.expr(["Equal",b,0]),matchPermutations:!1}]}if(f!=="Less"&&f!=="LessEqual"&&f!=="Greater"&&f!=="GreaterEqual")return[{pattern:c}];if(!m(c))return[{pattern:c}];let p=f==="Greater"||f==="GreaterEqual"?c.op2:c.op1,d=f==="Greater"||f==="GreaterEqual"?c.op1:c.op2,g=f==="Less"||f==="Greater"?"Less":"LessEqual",h=p.canonical.sub(d.canonical);return[{pattern:c},{pattern:e.expr([g,h,0]),matchPermutations:!1}]};if(m(t,"Element")){let c=t.op1,f=t.op2;if(w(c)&&We(f)){let p=fn(f);if(p&&!p.startsWith("__")){let d=e.expr(c.symbol).type;d.isUnknown||o({[p]:e.expr(d.toString(),{form:"raw"})})}}}if((t.operator==="Greater"||t.operator==="GreaterEqual"||t.operator==="Less"||t.operator==="LessEqual")&&m(t)&&We(t.op2)){let c=fn(t.op2);if(c&&!c.startsWith("__")){let f=t.operator==="Greater"||t.operator==="GreaterEqual",p=t.operator==="Greater"||t.operator==="Less",d=t.op1,g=Ft(d);if(g!==void 0){let h=rt(e,g),b=f?h.lower:h.upper,y=f?h.lowerStrict:h.upperStrict;b!==void 0&&(!p||y===!0)&&o({[c]:b})}if(We(d)){let h=fn(d);if(h&&!h.startsWith("__"))for(let b of a()){let y=rt(e,b),x=f?y.lower:y.upper,E=f?y.lowerStrict:y.upperStrict;x===void 0||p&&E!==!0||o({[h]:e.expr(b,{form:"canonical"}),[c]:x})}}}}if((t.operator==="Less"||t.operator==="LessEqual")&&m(t)&&We(t.op1)&&!We(t.op2)){let c=fn(t.op1);if(c&&!c.startsWith("__")){let f=t.operator==="Less",p=Ft(t.op2);if(p!==void 0){let d=rt(e,p);d.lower!==void 0&&(!f||d.lowerStrict===!0)&&o({[c]:d.lower})}}}let l=u(t);for(let[c,f]of s)if(f===!0)for(let{pattern:p,matchPermutations:d}of l){let g=c.match(p,{useVariations:!0,matchPermutations:d});g!==null&&o(g)}return i.length===0&&!r(t)&&!e._isVerifying&&ES(e,e.expr(n,{form:"canonical"}))===!0&&o({}),i}function ES(e,n){if(!e._isVerifying){e._isVerifying=!0;try{return Fb(e,n)}finally{e._isVerifying=!1}}}function Fb(e,n){let t=M6(e,n,"verify"),i=t.evaluate();if(w(i)){if(i.symbol==="True")return!0;if(i.symbol==="False")return!1}let r=i.operator;if(r==="Not"&&m(i)){let o=Fb(e,i.op1);return o===void 0?void 0:!o}if(r==="And"&&m(i)){let o=!1;for(let s of i.ops){let a=Fb(e,s);if(a===!1)return!1;a===void 0&&(o=!0)}return o?void 0:!0}if(r==="Or"&&m(i)){let o=!1;for(let s of i.ops){let a=Fb(e,s);if(a===!0)return!0;a===void 0&&(o=!0)}return o?void 0:!1}if(!C6(t)&&xS(e,t).some(s=>Object.keys(s).length===0))return!0}function C6(e){return e.operator.startsWith("_")||We(e)?!0:m(e)?e.ops.some(C6):!1}function k6(e,n){try{let t=M6(e,n,"assume").canonical;return e._generation+=1,e._mutationGeneration+=1,e.context&&(e.context._assumptionsDirty=!0),gS(t)}catch(t){throw console.error(t instanceof Error?t.message:String(t)),t}}function vS(e,n){if(n===void 0){e.context.assumptions?.clear();let t=e.context.assumptionBindings;if(t){for(let i of t){let r=e.context.lexicalScope.bindings.get(i);r&&ie(r)&&!r.value.isConstant&&(r.value.value=void 0)}t.clear()}e._generation+=1,e._mutationGeneration+=1,e.context&&(e.context._assumptionsDirty=!0);return}if(Array.isArray(n)){for(let t of n)vS(e,t);return}if(typeof n=="string"){for(let[i,r]of e.context.assumptions)i.has(n)&&e.context.assumptions.delete(i);let t=e.context.lexicalScope.bindings.get(n);t&&ie(t)&&!t.value.isConstant&&(t.value.value=void 0),e.context.assumptionBindings?.delete(n)}e._generation+=1,e._mutationGeneration+=1,e.context&&(e.context._assumptionsDirty=!0)}var A6="https://oeis.org";function fY(e){return typeof e=="object"&&e!==null?e:null}function pY(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isInteger(n)&&n>=0)return n}}function dY(e){return typeof e!="string"?[]:e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n))}function mY(e){if(!Array.isArray(e))return;let n=e.find(t=>typeof t=="string");return typeof n=="string"?n:void 0}function gY(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string");return n.length>0?n:void 0}function hY(e){if(typeof e=="string")return[e];if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string");return n.length>0?n:void 0}function bY(e){if(Array.isArray(e))return e;let n=fY(e);if(!n)return[];let t=n.results;return Array.isArray(t)?t:[]}function yY(e){return bY(e).map(t=>{let i=pY(t.number),r=i!==void 0?`A${String(i).padStart(6,"0")}`:"";return{id:r,name:typeof t.name=="string"?t.name:"",terms:dY(t.data),formula:mY(t.formula),formulas:gY(t.formula),comments:hY(t.comment),url:r?`${A6}/${r}`:""}})}async function Bb(e,n={}){let t=n.timeout??1e4,i=n.maxResults??5,r=e.join(","),o=`${A6}/search?fmt=json&q=${encodeURIComponent(r)}&start=0&count=${i}`;try{let s=new AbortController,a=setTimeout(()=>s.abort(),t),u=await fetch(o,{signal:s.signal,headers:{Accept:"application/json"}});if(clearTimeout(a),!u.ok)throw new Error(`OEIS request failed: ${u.status}`);let l=await u.json();return yY(l).slice(0,i)}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error("OEIS request timed out"):s}}async function R6(e,n,t={}){let i=n.map(r=>{if(typeof r=="number"){if(!Number.isInteger(r))throw new Error("OEIS lookup requires integer terms");return r}let o=r.re;if(!Number.isInteger(o))throw new Error("OEIS lookup requires integer terms");return o});return Bb(i,t)}async function P6(e,n,t=10,i={}){let r=e.getSequenceTerms(n,0,t-1);if(!r)throw new Error(`'${n}' is not a defined sequence`);let o=r.map(a=>a.re);return{matches:await Bb(o,i),terms:o}}function D6(e,n,t){if(!t.base||Object.keys(t.base).length===0)throw new Error(`Sequence "${n}" requires at least one base case`);if(!t.recurrence)throw new Error(`Sequence "${n}" requires a recurrence relation`);e.declare(n,{subscriptEvaluate:()=>{}});let i=I2(e,n,t);if(!i.valid)throw new Error(i.error);let r=w2(e,n,t),o=e.lookupDefinition(n);return o&&ie(o)&&(o.value.subscriptEvaluate=r),e}function O6(e,n){return K5(e,n)}function L6(e,n){return X5(e,n)}function F6(e){return eD(e)}function B6(e,n){return k2(e,n)}function $6(e,n){nD(e,n)}function q6(e,n){return tD(e,n)}function V6(e,n,t,i,r){return iD(e,n,t,i,r)}function J6(e,n,t){return R6(e,n,t)}function j6(e,n,t,i){return P6(e,n,t,i)}var xY=4,EY=[0,1,-1,2,-2,3,4];async function z6(e,n,t){let i=Np(n)??n,r=EE(n),o=vY(r);if(!r||!o||o.length<xY)return{expression:i,candidates:[]};let s;try{s=await Bb(o,t)}catch{return{expression:i,candidates:[]}}let a=[],u=new Set;for(let l of s){let c=SY(e,l,r);c&&!u.has(c.id)&&(u.add(c.id),a.push(c))}return{expression:i,candidates:a}}function vY(e){if(!e)return null;let n=[];for(let t of e){if(t.isInteger!==!0)return null;let i=t.re;if(!Number.isInteger(i))return null;n.push(i)}return n}function SY(e,n,t){if(!n.id)return null;for(let i of _Y(n))for(let r of NY(i)){let o=wY(e,r);if(o&&TY(o,t))return{expression:o,id:n.id,name:n.name,url:n.url,formula:i.trim()}}return null}function _Y(e){let n=e.formulas??(e.formula?[e.formula]:[]),t=[];for(let i of n)for(let r of i.split(`
|
|
139
139
|
`))t.push(r);return t}function NY(e){let n=/a\(\s*n\s*\)\s*=\s*(.+)$/i.exec(e);if(!n)return[];let t=n[1],i=t.search(/\s[-–—]\s_/);i>=0&&(t=t.slice(0,i));let r=t.search(/\s+(for|with|where|when|if)\s+/i);r>=0&&(t=t.slice(0,r));let o=[];for(let s of t.split("="))s=s.replace(/\.\s*$/,"").trim(),s&&(/\ba\s*\(/i.test(s)||o.push(s));return o}function wY(e,n){let t;try{t=e.parse(IY(n))}catch{return null}return!t||t.operator==="Error"||t.freeVariables.some(i=>i!=="n")?null:t}function IY(e){let n=e;return n=n.replace(/\bbinomial\(\s*([^(),]+?)\s*,\s*([^(),]+?)\s*\)/gi,"\\binom{$1}{$2}"),n=n.replace(/\bC\(\s*([^(),]+?)\s*,\s*([^(),]+?)\s*\)/g,"\\binom{$1}{$2}"),n=n.replace(/\bsqrt\(\s*([^()]*?)\s*\)/gi,"\\sqrt{$1}"),n=n.replace(/\bfloor\(\s*([^()]*?)\s*\)/gi,"\\lfloor $1 \\rfloor"),n=n.replace(/\bceiling\(\s*([^()]*?)\s*\)/gi,"\\lceil $1 \\rceil"),n}function TY(e,n){for(let t of EY)if(MY(e,n,t))return!0;return!1}function MY(e,n,t){for(let i=0;i<n.length;i++)if(!e.subs({n:t+i}).evaluate().isSame(n[i]))return!1;return!0}var $b=class{_entries={};getOrBuild(n,t,i){if(this._entries[n]===void 0)try{this._entries[n]={build:t,purge:i,value:t()}}catch(r){console.error(`Fatal error building cache "${n}":
|
|
140
|
-
${r}`)}return this._entries[n]?.value}invalidate(n){delete this._entries[n]}purgeValues(){for(let n of Object.keys(this._entries)){let t=this._entries[n];t.value&&(t.purge?t.value=t.purge(t.value):delete this._entries[n])}}};var hr=class e extends Je{_kind="symbol";_hash;_id;_def;constructor(n,t,i){super(n,i?.metadata),yn(t),`${t}${vi(t)}`,this._id=t,this._def=i?.def}get json(){return Li(this._id)?this._id:{sym:this._id}}get hash(){return this._hash??=Fi(this._id),this._hash}_unshared(){return new e(this.engine,this._id,{metadata:{latex:this.verbatimLatex,sourceOffsets:this.sourceOffsets},def:this._def})}get isPure(){return!0}get isConstant(){let n=this._def;return(ie(n)&&n?.value.isConstant)??!1}bind(){}reset(){}get isCanonical(){return this._def!==void 0}set isCanonical(n){throw new Error("Setting the isCanonical property is not allowed. Use the canonical() method instead.")}get canonical(){return this._def?this:this.engine.symbol(this._id)}is(n,t){if(t===void 0&&this.isSame(n))return!0;let i=this.value;return i&&i!==this?i.is(n,t):!1}isSame(n){return n===!0?this.symbol==="True"||w(this.value,"True"):n===!1?this.symbol==="False"||w(this.value,"False"):n instanceof Je&&w(n)?this.symbol===n.symbol:this.value?.isSame(n)??!1}toNumericValue(){this.isCanonical||this.isStructural;let n=this.engine;return this.symbol==="ImaginaryUnit"?[n._numericValue({re:0,im:1}),n.One]:this.symbol==="PositiveInfinity"||this.isInfinity&&this.isPositive?[n._numericValue(1/0),n.One]:this.symbol==="NegativeInfinity"||this.isInfinity&&this.isNegative?[n._numericValue(-1/0),n.One]:this.symbol==="NaN"?[n._numericValue(NaN),n.One]:[n._numericValue(1),this]}neg(){return $a(this)}inv(){return this.engine._fn("Divide",[this.engine.One,this])}abs(){return this.isNonNegative?this:this.isNonPositive?this.neg():this.engine._fn("Abs",[this])}add(n){return n===0?this:te(this,this.engine.expr(n))}mul(n){if(n===1)return this;if(n===-1)return this.neg();if(n===0||n instanceof je&&n.isZero)return this.isNaN||this.isInfinity===!0?this.engine.NaN:this.engine.Zero;if(n instanceof je){if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return he(this,this.engine.expr(n))}div(n){return ll(this,n)}pow(n){return sn(this,n,{numericApproximation:!1})}root(n){let t=typeof n=="number"?n:n.im===0?n.re:void 0,i=this.engine;return this.symbol==="ComplexInfinity"||t===0?i.NaN:t===1?this:t===2?this.sqrt():t===-1?this.inv():t!==void 0&&t<0&&Number.isInteger(t)?i._fn("Divide",[i.One,this.root(-t)]):i._fn("Root",[this,i.expr(n)])}sqrt(){let n=this.engine;return this.symbol==="ComplexInfinity"?n.NaN:n._fn("Sqrt",[this])}ln(n){let t=n?this.engine.expr(n):void 0;return this.symbol==="ExponentialE"?!t||w(t,"ExponentialE")?this.engine.One:this.engine.One.div(t.ln()):t?t.re===10?this.engine._fn("Log",[this]):this.engine._fn("Log",[this,t]):this.engine._fn("Ln",[this])}solve(n){let t=La(n);return t.length!==1?null:t.includes(this.symbol)?[this.engine.Zero]:null}get complexity(){return 7}get operator(){return"Symbol"}get symbol(){return this._id}get baseDefinition(){return this.valueDefinition??this.operatorDefinition}get valueDefinition(){if(ie(this._def))return this._def.value}get operatorDefinition(){if(fe(this._def))return this._def.operator}infer(n,t="narrow"){if(!this._def)return!1;let i=this._def;if(ie(i)){if(i.value.isConstant)return!1;if(i.value.inferredType||i.value.type.isUnknown){let r=i.value.type.isUnknown,o=this.engine.type(t==="widen"?Te(i.value.type.type,n):fs(i.value.type.type,n));return o.isUnknown?!1:(i.value.type=o,r&&this.engine._inferenceTxDepth>0&&(this.engine._freshlyInferred??=new Set).add(i.value),!0)}return!1}if(fe(i)){let r=this.engine.type(t==="widen"?Te(i.operator.signature.type,n):fs(i.operator.signature.type,n));return r.matches("never")?!1:r.matches("function")?(i.operator.signature=r,this.engine._mutationGeneration+=1,!0):(Si(this.engine,this._id,i,{type:r.type}),!0)}return!1}get _value(){if(!this._def||fe(this._def))return;if(this._def.value.isConstant)return this._def.value.value;if(this._def.value.isSelfReferential)return;let n=this.engine._getSymbolValue(this._id);if(!(n!==void 0&&"symbol"in n&&n.symbol===this._id))return n}get value(){return fe(this._def)?this.engine._fn("Operator",[this.engine.string(this._id)]):this._value}set value(n){if(!this._def)throw new Error(`Cannot set value of non-canonical ${this._id}`);let t=this.engine;t.forget(this._id);let i;if(typeof n=="boolean"&&(n=n?t.True:t.False),typeof n=="string"&&(n=t.string(n)),typeof n=="object")if("re"in n&&"im"in n)n=t.number(t.complex(n.re??0,n.im));else if("num"in n&&"denom"in n)n=t.number([n.num,n.denom]);else if(Array.isArray(n))n=t._fn("List",n.map(r=>t.expr(r)));else throw new Error(`Invalid value for symbol ${this._id}: ${n}`);if(n!==void 0&&(i=t.expr(n).evaluate()),i?.type.matches("function")){delete this._def.value,this._def.operator={signature:i.type,evaluate:i};return}if(ie(this._def)&&this._def.value.isConstant)throw new Error(`The value of the constant "${this._id}" cannot be changed`);t._setSymbolValue(this._id,i)}get type(){let n=this._def;return ie(n)?n.value.type:fe(n)?n.operator.signature:Z.unknown}set type(n){if(!this._def)throw new Error(`Cannot set type of non-canonical symbol "${this._id}"`);if(this._id[0]==="_")throw new Error(`The type of the wildcard "${this._id}" cannot be changed`);this.engine.forget(this._id),typeof n=="string"?n=Y(n):n instanceof Z&&(n=n.type),n==="function"||jd(n)?fe(this._def)?this._def.operator.signature=n:Si(this.engine,this._id,this._def,{signature:n}):fe(this._def)?Si(this.engine,this._id,this._def,{type:n}):this._def.value.type=this.engine.type(n)}has(n){return typeof n=="string"?this._id===n:n.includes(this._id)}match(n,t){return Bl(this,n,t)}get shape(){let n=this.type.type;return typeof n=="object"&&n.kind==="list"&&n.dimensions?n.dimensions:[]}get rank(){return this.shape.length}get sgn(){return this.value?this.value.sgn:T6(this.engine,this.symbol)}get isOdd(){return this.value?.isOdd}get isEven(){return this.value?.isEven}get isFinite(){let n=this.value?.isFinite;if(n!==void 0)return n;let t=this.type;if(!t.isUnknown&&t.matches("finite_number"))return!0}get isInfinity(){return this.value?.isInfinity}get isNaN(){return this.value?.isNaN}get isPositive(){return $l(this.sgn)}get isNonPositive(){return Jl(this.sgn)}get isNegative(){return Vl(this.sgn)}get isNonNegative(){return ql(this.sgn)}get isNumber(){let n=this.type;if(!n.isUnknown)return n.matches("number")}get isInteger(){let n=this.type;if(!n.isUnknown){if(n.matches("integer"))return!0;if(!n.matches("real")){if(n.matches("number"))return gi(n.type)?!1:void 0;if(Bn({kind:"intersection",types:[n.type,"integer"]})==="nothing")return!1}}}get isRational(){let n=this.type;if(!n.isUnknown){if(n.matches("rational"))return!0;if(!n.matches("real")){if(n.matches("number"))return gi(n.type)?!1:void 0;if(Bn({kind:"intersection",types:[n.type,"rational"]})==="nothing")return!1}}}get isReal(){let n=this.type;if(!n.isUnknown){if(n.matches("real"))return!0;if(Xi(this.engine)&&_r(this.engine).membership.get(this._id)?.notIn.some(i=>w(i,"RealNumbers")))return!1;if(!(n.matches("number")&&!gi(n.type)))return!1}}get re(){return this.value?.re??NaN}get im(){return this.value?.im??NaN}get bignumRe(){return this.value?.bignumRe}get bignumIm(){return this.value?.bignumIm}simplify(n){return Qr(this,n).at(-1)?.value??this}explain(n,t){return Fl(this,n,t)}evaluate(n){let t=this.valueDefinition;if(!t)return this;let i=t.holdUntil;if(t.isConstant){if(n?.numericApproximation){if(i==="never"||i==="evaluate"||i==="N")return t.value?.N()??this}else if(i==="never"||i==="evaluate")return t.value?.evaluate(n)??this}else if(i==="never"||i==="evaluate"||i==="N"&&n?.numericApproximation){let r=this.engine._getSymbolValue(this._id)??this;return r.operator==="Unevaluated"&&(r=r.evaluate(n)??this),r}return this}N(){let n=this.valueDefinition;if(n&&!n.isConstant){let t=this._value;return t?N(t)?t.N():t.symbols.includes(this._id)?t:t.N():this}return n?.value?.N()??this}replace(n,t){return es(this,n,t).at(-1)?.value??null}subs(n,t){let i=t?.canonical??this.isCanonical;if(n[this._id]===void 0)return i?this.canonical:this;let r=i===!0?"canonical":i===!1?"raw":i;return this.engine.expr(n[this._id],{form:r})}get _asCollection(){if(ie(this._def))return this._def.value.collection}get isCollection(){return this._asCollection?.iterator!==void 0||(this._value?.isCollection??!1)}get isIndexedCollection(){return this._asCollection?.at!==void 0||(this._value?.isIndexedCollection??!1)}get isLazyCollection(){return this._asCollection?.isLazy?.(this._value??this)??this._value?.isLazyCollection??!1}contains(n){return this._asCollection?.contains?.(this._value??this,n)??this._value?.contains?.(n)}get count(){return this._asCollection?.count(this._value??this)??this._value?.count}get isEmptyCollection(){return this._asCollection?.isEmpty?.(this._value??this)??this._value?.isEmptyCollection}get isFiniteCollection(){return this._asCollection?.isFinite?.(this._value??this)??this._value?.isFiniteCollection}each(){let n=this._asCollection?.iterator?.(this._value??this);if(n){let t=this.engine;return(function*(){let i=n.next(),r=0;for(;!i.done;)(++r&255)===0&&z(t._deadline),yield i.value,i=n.next()})()}return this._value?.each()??(function*(){})()}at(n){let t=this._asCollection?.at;if(t){let i=this._value??this;if(n<0){if(this.isFiniteCollection!==!0)return this._value?.at?.(n);let o=this.count;if(o!==void 0&&Number.isFinite(o)){let s=o+1+n;if(s>=1){let a=t(i,s);if(a!==void 0)return a}return this._value?.at?.(n)}return this._value?.at?.(n)}let r=t(i,n);if(r!==void 0)return r}return this._value?.at?.(n)}get(n){return this._value?.get?.(n)}indexWhere(n){return this._asCollection?.indexWhere?this._asCollection.indexWhere(this._value??this,n):this._value?.indexWhere(n)}subsetOf(n,t){return this._asCollection?.subsetOf?.(this._value??this,n,t)??this._value?.subsetOf?.(n,t)??!1}};function CY(e,n){return e.lookupDefinition(n)}function G6(e,n){for(let t of Object.keys(n))n[t]=new hr(e,t,{def:CY(e,t)})}function U6(e){for(let n of Object.values(e))n?.reset()}function Jn(e){if(!Number.isFinite(e))throw new Error(`Cannot compile the non-finite value \`${e}\` to a GPU shader: GLSL/WGSL have no infinity or NaN literals.`);let n=e.toString();return!n.includes(".")&&!n.includes("e")&&!n.includes("E")?`${n}.0`:n}function Qe(e){if(!N(e)||e.im!==0)return;let n=e.re;if(isFinite(n))return n}var kY=/^-?\d+(\.\d+)?$/;function ra(e,n,t){let i=t==="+"?0:1,r=null,o=[];for(let s of e)if(kY.test(s)){let a=parseFloat(s);if(t==="*"&&a===0)return"0.0";r===null?r=a:r=t==="+"?r+a:r*a}else o.push(s);return r!==null&&r!==i&&o.unshift(Jn(r)),o.length===0?r!==null?Jn(r):n:o.length===1?o[0]:o.join(t==="+"?" + ":" * ")}function qb(e,n){return m(e,"Add")||m(e,"Subtract")?`(${n})`:n}function Z6(e,n){if(w(e,"ImaginaryUnit"))return{re:null,im:"1.0"};if(N(e)&&e.im!==0){let t=e.re,i=e.im;return{re:t!==0?Jn(t):null,im:Jn(i)}}if(m(e,"Multiply")){let t=e.ops,i=t.findIndex(r=>w(r,"ImaginaryUnit")||N(r)&&r.re===0&&r.im!==0);if(i>=0){let r=t[i],o=w(r,"ImaginaryUnit")?1:r.im,s=t.filter((l,c)=>c!==i);if(s.length===0)return{re:null,im:Jn(o)};let a=s.map(l=>qb(l,n(l)));return o!==1&&a.unshift(Jn(o)),{re:null,im:ra(a,"1.0","*")}}}return D.isComplexValued(e)?null:{re:n(e),im:null}}var SS={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],Divide:["/",13],LessEqual:["<=",9],GreaterEqual:[">=",9],Less:["<",9],Greater:[">",9],And:["&&",4],Or:["||",3],Not:["!",14]};function H6(e,n,t){if(n.length<2)throw new Error(`${e}: expected at least two arguments`);let i=n[0]?.engine?.tolerance??1e-10,r=l=>l.type.matches("collection")||tO(l);if(n.some(r)){if(n.length===2)return`_SYS.${e==="Equal"?"eq":"neq"}((${t(n[0])}), (${t(n[1])}), ${i})`;throw new Error(`${e}: cannot compile \u2014 chained (n-ary) comparison over an operand that may be a collection at run time (collection-valued or possibly-collection-typed). Materialize the collection first. Fail closed (D6).`)}let o=e==="Equal"?"<=":">",s=(l,c)=>{if(!(D.isComplexValued(l)||D.isComplexValued(c)))return`Math.abs((${t(l)}) - (${t(c)}))`;let p=h=>{let b=t(h);return D.isComplexValued(h)?{re:`(${b}).re`,im:`(${b}).im`}:{re:`(${b})`,im:"0"}},d=p(l),g=p(c);return`_SYS.cabs({ re: ${d.re} - ${g.re}, im: ${d.im} - ${g.im} })`},a=(l,c)=>`(${s(l,c)} ${o} ${i})`;if(n.length===2)return a(n[0],n[1]);let u=[];for(let l=0;l<n.length-1;l++)u.push(a(n[l],n[l+1]));return`(${u.join(" && ")})`}function go(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}function tO(e){let n=e.type.type;return n==="unknown"||n==="any"||n==="value"?m(e)&&(e.isCanonical||e.isStructural):typeof n!="string"&&n.kind==="broadcastable"}function _S(e,n,t){let i=t(e),r=e.type.type;return typeof r!="string"&&r.kind==="tuple"?`${i}[${n}]`:AY(e)?`(${i}).map((_pt) => _pt[${n}])`:`${i}[${n}]`}function AY(e){let n=De(e.type.type);if(n!==void 0&&typeof n!="string"&&n.kind==="tuple")return!0;if(e.isFiniteCollection){let t=e.at(1);if(t===void 0)return!1;let i=t.type.type;return typeof i!="string"&&i.kind==="tuple"||t.operator==="Tuple"}return!1}var NS={Equal:(e,n)=>H6("Equal",e,n),NotEqual:(e,n)=>H6("NotEqual",e,n),Abs:(e,n)=>D.isComplexValued(e[0])?`_SYS.cabs(${n(e[0])})`:D.isNonNegative(e[0])?n(e[0]):`Math.abs(${n(e[0])})`,Add:(e,n)=>{if(e.length===1)return n(e[0]);if(!e.some(s=>D.isComplexValued(s))){let s=e.map(Qe);if(s.every(u=>u!==void 0))return String(s.reduce((u,l)=>u+l,0));let a=e.filter(u=>Qe(u)!==0);return a.length===0?"0":a.length===1?n(a[0]):`(${a.map(u=>n(u)).join(" + ")})`}let i=e.map(s=>({code:n(s),isComplex:D.isComplexValued(s)})),r=i.map(s=>s.isComplex?`(${s.code}).re`:s.code),o=i.filter(s=>s.isComplex).map(s=>`(${s.code}).im`);return`({ re: ${r.join(" + ")}, im: ${o.join(" + ")} })`},Arccos:(e,n)=>D.isComplexValued(e[0])?`_SYS.cacos(${n(e[0])})`:`Math.acos(${n(e[0])})`,Arcosh:"Math.acosh",Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return D.isComplexValued(e)?`_SYS.cacot(${n(e)})`:`(Math.PI / 2 - Math.atan(${n(e)}))`},Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return D.isComplexValued(e)?`_SYS.cacoth(${n(e)})`:`Math.atanh(1 / (${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return D.isComplexValued(e)?`_SYS.cacsc(${n(e)})`:`Math.asin(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return D.isComplexValued(e)?`_SYS.cacsch(${n(e)})`:`Math.asinh(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return D.isComplexValued(e)?`_SYS.casec(${n(e)})`:`Math.acos(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return D.isComplexValued(e)?`_SYS.casech(${n(e)})`:`Math.acosh(1 / (${n(e)}))`},Arcsin:(e,n)=>D.isComplexValued(e[0])?`_SYS.casin(${n(e[0])})`:`Math.asin(${n(e[0])})`,Arsinh:"Math.asinh",Arctan:(e,n)=>D.isComplexValued(e[0])?`_SYS.catan(${n(e[0])})`:`Math.atan(${n(e[0])})`,Artanh:"Math.atanh",Ceil:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.ceil(${n(e[0])})`,Chop:"_SYS.chop",Cos:(e,n)=>D.isComplexValued(e[0])?`_SYS.ccos(${n(e[0])})`:`Math.cos(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`_SYS.ccosh(${n(e[0])})`:`Math.cosh(${n(e[0])})`,Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");return D.isComplexValued(e)?`_SYS.ccot(${n(e)})`:D.inlineExpression("Math.cos(${x}) / Math.sin(${x})",n(e))},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return D.isComplexValued(e)?`_SYS.ccoth(${n(e)})`:D.inlineExpression("(Math.cosh(${x}) / Math.sinh(${x}))",n(e))},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return D.isComplexValued(e)?`_SYS.ccsc(${n(e)})`:`1 / Math.sin(${n(e)})`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return D.isComplexValued(e)?`_SYS.ccsch(${n(e)})`:`1 / Math.sinh(${n(e)})`},Exp:(e,n)=>D.isComplexValued(e[0])?`_SYS.cexp(${n(e[0])})`:`Math.exp(${n(e[0])})`,First:(e,n)=>`${n(e[0])}[0]`,Floor:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.floor(${n(e[0])})`,Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return D.inlineExpression("${x} - Math.floor(${x})",n(e))},Gamma:"_SYS.gamma",GCD:(e,n)=>eO("GCD",e,n),Integrate:(e,n,t)=>VY(e,n,t),LCM:(e,n)=>eO("LCM",e,n),Product:(e,n,t)=>W6("Product",e,n,t),Sum:(e,n,t)=>W6("Sum",e,n,t),Limit:(e,n)=>`_SYS.limit(${n(e[0])}, ${n(e[1])})`,Ln:(e,n)=>D.isComplexValued(e[0])?`_SYS.cln(${n(e[0])})`:`Math.log(${n(e[0])})`,List:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Matrix:(e,n)=>n(e[0]),Tuple:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Length:(e,n)=>{let t=e[0];if(t==null)throw new Error("Length: no argument");if(!go(t))throw new Error("Length: cannot compile \u2014 operand is not an indexed collection (list/vector/range). Fail closed (D6).");return`(${n(t)}).length`},At:(e,n)=>{let t=e[0],i=e[1];if(t==null||i===null||i===void 0)throw new Error("At: missing argument");if(e.length!==2)throw new Error("At: only the single-index form compiles; multi-index (nested) access is not supported. Fail closed (D6).");if(!go(t))throw new Error("At: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");return`_SYS.at(${n(t)}, ${n(i)})`},Reduce:(e,n,t)=>{let i=e[0],r=e[1],o=e[2];if(i==null||r===null||r===void 0)throw new Error("Reduce: missing argument");if(!go(i))throw new Error("Reduce: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=Q6(r);if(s===void 0&&(m(r,"Function")||w(r))){if(o==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");s=K6(r,n,t)}if(s===void 0)throw new Error("Reduce: the combiner does not compile to a function \u2014 only Add/Multiply/Min/Max folds, function literals, and user-defined functions compile on the JavaScript target. Fail closed (D6).");let a=n(i);return o!=null?`(${a}).reduce(${s}, ${n(o)})`:`((_l) => _l.length === 0 ? NaN : _l.reduce(${s}))(${a})`},Last:(e,n)=>`_SYS.at(${ve("Last",e[0],n)}, -1)`,Rest:(e,n)=>`(${ve("Rest",e[0],n)}).slice(1)`,Take:(e,n)=>{let t=ve("Take",e[0],n);if(e[1]==null)throw new Error("Take: missing count");return`(${t}).slice(0, Math.max(0, ${n(e[1])}))`},Drop:(e,n)=>{let t=ve("Drop",e[0],n);if(e[1]==null)throw new Error("Drop: missing count");return`(${t}).slice(Math.max(0, ${n(e[1])}))`},Reverse:(e,n)=>`(${ve("Reverse",e[0],n)}).slice().reverse()`,Sort:(e,n)=>{let t=ve("Sort",e[0],n);if(e.length>1)throw new Error("Sort: a custom comparator does not compile; only the default ascending numeric sort is supported. Fail closed (D6).");return`(${t}).slice().sort((_a, _b) => _a - _b)`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`...(${ve("Join",t,n,i+1)})`).join(", ")}]`,IndexOf:(e,n)=>{let t=ve("IndexOf",e[0],n);if(e[1]==null)throw new Error("IndexOf: missing value");let i=e[0]?.engine?.tolerance??1e-10;return`((_v) => (${t}).findIndex((_x) => Math.abs(_x - _v) <= ${i}) + 1)(${n(e[1])})`},Map:(e,n)=>{if(e.length>2)throw new Error("Map: multi-collection form is not compiled");let t=ve("Map",e[0],n);if(e[1]==null)throw new Error("Map: missing mapping function");return`((_f) => (${t}).map((_x) => _f(_x)))(${n(e[1])})`},Filter:(e,n)=>{let t=ve("Filter",e[0],n);if(e[1]==null)throw new Error("Filter: missing predicate");return`((_f) => (${t}).filter((_x) => _f(_x)))(${n(e[1])})`},CountIf:(e,n)=>{let t=ve("CountIf",e[0],n);if(e[1]==null)throw new Error("CountIf: missing predicate");return`((_f) => (${t}).filter((_x) => _f(_x)).length)(${n(e[1])})`},Find:(e,n)=>{let t=ve("Find",e[0],n);if(e[1]==null)throw new Error("Find: missing predicate");return`((_f) => ((${t}).find((_x) => _f(_x)) ?? NaN))(${n(e[1])})`},IndexWhere:(e,n)=>{let t=ve("IndexWhere",e[0],n);if(e[1]==null)throw new Error("IndexWhere: missing predicate");return`((_f) => (${t}).findIndex((_x) => _f(_x)) + 1)(${n(e[1])})`},Position:(e,n)=>{let t=ve("Position",e[0],n);if(e[1]==null)throw new Error("Position: missing predicate");return`((_f) => (${t}).flatMap((_x, _i) => _f(_x) ? [_i + 1] : []))(${n(e[1])})`},Tabulate:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Tabulate: missing argument");if(e.length>3)throw new Error("Tabulate: only the 1-D and 2-D forms compile. Fail closed (D6).");for(let o=1;o<e.length;o++){let s=Qe(e[o]);if(s!==void 0&&Math.round(s)<=0)throw new Error(`Tabulate: a statically non-positive dimension (${s}) is inert in the interpreter. Fail closed (D6).`)}let t=n(e[0]),i=n(e[1]);if(e.length===2)return`((_f, _n) => Array.from({ length: Math.max(0, Math.round(_n)) }, (_, _i) => _f(_i + 1)))(${t}, ${i})`;let r=n(e[2]);return`((_f, _n, _m) => Array.from({ length: Math.max(0, Math.round(_n)) }, (_, _i) => Array.from({ length: Math.max(0, Math.round(_m)) }, (_, _j) => _f(_i + 1, _j + 1))))(${t}, ${i}, ${r})`},Fill:(e,n)=>{let t=e[1];if(e[0]==null||t==null)throw new Error("Fill: missing argument");if(!m(t)||t.ops.length!==2)throw new Error("Fill: only the (function, (rows, cols)) form compiles. Fail closed (D6).");let i=n(e[0]),r=n(t.ops[0]),o=n(t.ops[1]);return`((_f, _r, _c) => Array.from({ length: Math.max(0, Math.round(_r)) }, (_, _i) => Array.from({ length: Math.max(0, Math.round(_c)) }, (_, _j) => _f(_i + 1, _j + 1))))(${i}, ${r}, ${o})`},Append:(e,n)=>{let t=ve("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[...(${t}), ${n(e[1])}]`},Most:(e,n)=>`(${ve("Most",e[0],n)}).slice(0, -1)`,Slice:(e,n)=>{let t=ve("Slice",e[0],n);if(e[1]==null||e[2]==null)throw new Error("Slice: missing index");return`((_l, _s, _e) => { _s = Math.round(_s); if (!Number.isFinite(_s)) _s = 1; _e = Math.round(_e); if (!Number.isFinite(_e)) _e = _l.length; if (_s < 1) _s = _l.length + 1 + _s; if (_s < 1) _s = 1; if (_s > _l.length) return []; if (_e < 1) _e = _l.length + 1 + _e; if (_e < 1) _e = 1; if (_e > _l.length) _e = _l.length; return _l.slice(_s - 1, _e); })(${t}, ${n(e[1])}, ${n(e[2])})`},IsEmpty:(e,n)=>`((${ve("IsEmpty",e[0],n)}).length === 0)`,Count:(e,n)=>`(${ve("Count",e[0],n)}).length`,Contains:(e,n)=>{e[0]&&du("Contains",e[0]);let t=ve("Contains",e[0],n);if(e[1]==null)throw new Error("Contains: missing value");return`(${t}).includes(${n(e[1])})`},Unique:(e,n)=>(e[0]&&du("Unique",e[0]),`[...new Set(${ve("Unique",e[0],n)})]`),RotateLeft:(e,n)=>{let t=ve("RotateLeft",e[0],n),i=e[1]==null?"1":n(e[1]);return`((_l, _n) => { if (_l.length === 0) return []; _n = Math.round(_n); if (!Number.isFinite(_n)) _n = 1; _n = ((_n % _l.length) + _l.length) % _l.length; return [..._l.slice(_n), ..._l.slice(0, _n)]; })(${t}, ${i})`},RotateRight:(e,n)=>{let t=ve("RotateRight",e[0],n),i=e[1]==null?"1":n(e[1]);return`((_l, _n) => { if (_l.length === 0) return []; _n = Math.round(_n); if (!Number.isFinite(_n)) _n = 1; _n = ((-_n % _l.length) + _l.length) % _l.length; return [..._l.slice(_n), ..._l.slice(0, _n)]; })(${t}, ${i})`},Zip:(e,n)=>e.length===0?"[]":`((..._ls) => Array.from({ length: Math.min(..._ls.map((_l) => _l.length)) }, (_, _i) => _ls.map((_l) => _l[_i])))(${e.map((i,r)=>ve("Zip",i,n,r+1)).join(", ")})`,Linspace:(e,n)=>{if(e[0]==null)throw new Error("Linspace: missing argument");let t=e[1]==null?"1":n(e[0]),i=e[1]==null?n(e[0]):n(e[1]),r=e[2]==null?"50":n(e[2]);return`((_s, _e, _c) => { _c = Math.floor(_c); if (!Number.isFinite(_c)) _c = 50; _c = Math.max(0, _c); if (_c === 1) return [_s]; return Array.from({ length: _c }, (_, _i) => _s + ((_e - _s) * _i) / (_c - 1)); })(${t}, ${i}, ${r})`},Chunk:(e,n)=>{let t=ve("Chunk",e[0],n);if(e[1]==null)throw new Error("Chunk: missing count");let i=Qe(e[1]);if(i!==void 0&&!(Math.round(i)>0))throw new Error(`Chunk: a statically non-positive chunk count (${i}) is inert in the interpreter. Fail closed (D6).`);return`((_l, _k) => { _k = Math.round(_k); if (!(Number.isFinite(_k) && _k > 0)) return []; const _sz = Math.ceil(_l.length / _k); return Array.from({ length: _k }, (_, _i) => _l.slice(_i * _sz, (_i + 1) * _sz)); })(${t}, ${n(e[1])})`},Partition:(e,n)=>{let t=ve("Partition",e[0],n),i=e[1];if(i==null)throw new Error("Partition: missing operand");if(i.type.matches("number")){let r=Qe(i);if(r!==void 0&&!(Math.round(r)>0))throw new Error(`Partition: a statically non-positive chunk size (${r}) is inert in the interpreter. Fail closed (D6).`);let o=e[2];if(o!==void 0){let s=Qe(o);if(s!==void 0&&!(Math.round(s)>0))throw new Error(`Partition: a statically non-positive step (${s}) is inert in the interpreter. Fail closed (D6).`);return`((_l, _n, _s) => { _n = Math.round(_n); _s = Math.round(_s); if (!(Number.isFinite(_n) && _n > 0 && Number.isFinite(_s) && _s > 0)) return []; const _r = []; for (let _i = 0; _i + _n <= _l.length; _i += _s) _r.push(_l.slice(_i, _i + _n)); return _r; })(${t}, ${n(i)}, ${n(o)})`}return`((_l, _n) => { _n = Math.round(_n); if (!(Number.isFinite(_n) && _n > 0)) return []; const _r = []; for (let _i = 0; _i < _l.length; _i += _n) _r.push(_l.slice(_i, _i + _n)); return _r; })(${t}, ${n(i)})`}if(m(i,"Function")||w(i)&&D.userFunctionLiteral(i.engine,i.symbol)!==void 0)return`((_f, _l) => { const _t = [], _u = []; for (const _x of _l) (_f(_x) ? _t : _u).push(_x); return [_t, _u]; })(${n(i)}, ${t})`;throw new Error("Partition: the second operand must be an integer or a function literal. Fail closed (D6).")},Ordering:(e,n)=>{let t=ve("Ordering",e[0],n);if(e.length>1)throw new Error("Ordering: a custom ordering function does not compile; only the default ascending numeric order is supported. Fail closed (D6).");return`((_l) => Array.from({ length: _l.length }, (_, _i) => _i + 1).sort((_a, _b) => _l[_a - 1] - _l[_b - 1]))(${t})`},Shuffle:(e,n,t)=>{let i=ve("Shuffle",e[0],n);if(e.length>1)throw new Error("Shuffle: the seeded form does not compile. Fail closed (D6).");let r=t?.randomSeed;if(r!=null){let o=t?.randomState?t.randomState.counter++:0,s=(r^Math.imul(o+1,2654435761))>>>0;return`_SYS.shuffle(${i}, ${s})`}return`_SYS.shuffle(${i})`},Any:(e,n)=>{let t=ve("Any",e[0],n);if(e[1]==null)throw new Error("Any: only the predicate form compiles. Fail closed (D6).");return`((_f) => (${t}).some((_x) => _f(_x)))(${n(e[1])})`},All:(e,n)=>{let t=ve("All",e[0],n);if(e[1]==null)throw new Error("All: only the predicate form compiles. Fail closed (D6).");return`((_f) => (${t}).every((_x) => _f(_x)))(${n(e[1])})`},TakeWhile:(e,n)=>{let t=ve("TakeWhile",e[0],n);if(e[1]==null)throw new Error("TakeWhile: missing predicate");return`((_f, _l) => { const _i = _l.findIndex((_x) => !_f(_x)); return _i < 0 ? _l.slice() : _l.slice(0, _i); })(${n(e[1])}, ${t})`},DropWhile:(e,n)=>{let t=ve("DropWhile",e[0],n);if(e[1]==null)throw new Error("DropWhile: missing predicate");return`((_f, _l) => { const _i = _l.findIndex((_x) => !_f(_x)); return _i < 0 ? [] : _l.slice(_i); })(${n(e[1])}, ${t})`},FlatMap:(e,n)=>{let t=ve("FlatMap",e[0],n);if(e[1]==null)throw new Error("FlatMap: missing mapping function");return`((_f) => (${t}).flatMap((_x) => _f(_x)))(${n(e[1])})`},Scan:(e,n,t)=>{let i=e[0],r=e[1],o=e[2];if(i==null||r==null)throw new Error("Scan: missing argument");if(!go(i))throw new Error("Scan: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=Q6(r)??(m(r,"Function")||w(r)?K6(r,n,t):void 0);if(s===void 0)throw new Error("Scan: the combiner does not compile to a function \u2014 only Add/Multiply/Min/Max folds, function literals, and user-defined functions compile on the JavaScript target. Fail closed (D6).");let a=n(i);return o!=null?`((_f, _l, _a) => _l.map((_x) => (_a = _f(_a, _x))))(${s}, ${a}, ${n(o)})`:`((_f, _l) => { let _a; return _l.map((_x, _i) => (_a = _i === 0 ? _x : _f(_a, _x))); })(${s}, ${a})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");let t=n(e[0]);return D.isBooleanValued(e[0])?`((${t}) ? 1 : 0)`:`(_SYS.cond(${t}) ? 1 : 0)`},KroneckerDelta:(e,n)=>{if(e.length===0||e[0]==null)throw new Error("KroneckerDelta: missing argument");let t=e[0].engine.tolerance??1e-10;return e.length===1?`(Math.abs(${n(e[0])}) <= ${t} ? 1 : 0)`:`((..._v) => _v.every((_x) => Math.abs(_x - _v[0]) <= ${t}) ? 1 : 0)(${e.map(i=>n(i)).join(", ")})`},Element:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Element: missing argument");return du("Element",e[1]),`(${ve("Element",e[1],n)}).includes(${n(e[0])})`},Identity:(e,n)=>{if(e[0]==null)throw new Error("Identity: missing argument");return n(e[0])},Apply:(e,n)=>{if(e[0]==null)throw new Error("Apply: missing function");return`(${n(e[0])})(${e.slice(1).map(t=>n(t)).join(", ")})`},Dot:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Dot: missing argument");return`_SYS.matmul(${ve("Dot",e[0],n,1)}, ${ve("Dot",e[1],n,2)})`},MatrixMultiply:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixMultiply: missing argument");return`_SYS.matmul(${ve("MatrixMultiply",e[0],n,1)}, ${ve("MatrixMultiply",e[1],n,2)})`},Cross:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Cross: missing argument");return`_SYS.cross(${ve("Cross",e[0],n,1)}, ${ve("Cross",e[1],n,2)})`},Norm:(e,n)=>{if(e[0]==null)throw new Error("Norm: missing argument");if(e[1]!=null){if(q(e[1])){if(e[1].string==="Frobenius")return`_SYS.norm(${n(e[0])})`;throw new Error(`Norm: the "${e[1].string}" norm does not compile. Fail closed (D6).`)}return`_SYS.norm(${n(e[0])}, ${n(e[1])})`}return`_SYS.norm(${n(e[0])})`},Transpose:(e,n)=>{if(e.length>1)throw new Error("Transpose: explicit axes do not compile. Fail closed (D6).");return`_SYS.transpose(${ve("Transpose",e[0],n)})`},Determinant:(e,n)=>`_SYS.det(${ve("Determinant",e[0],n)})`,Inverse:(e,n)=>`_SYS.inv(${ve("Inverse",e[0],n)})`,Trace:(e,n)=>{if(e.length>1)throw new Error("Trace: explicit axes do not compile. Fail closed (D6).");return`_SYS.trace(${ve("Trace",e[0],n)})`},ConjugateTranspose:(e,n)=>{if(e.length>1)throw new Error("ConjugateTranspose: explicit axes do not compile. Fail closed (D6).");return`_SYS.conjTranspose(${ve("ConjugateTranspose",e[0],n)})`},Diagonal:(e,n)=>{if(e.length>1)throw new Error("Diagonal: the offset/banded form does not compile. Fail closed (D6).");return`_SYS.diagonal(${ve("Diagonal",e[0],n)})`},MatrixPower:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixPower: missing argument");return`_SYS.matpow(${ve("MatrixPower",e[0],n)}, ${n(e[1])})`},RowReduce:(e,n)=>`_SYS.rref(${ve("RowReduce",e[0],n)})`,Rank:(e,n)=>{if(e[0]==null)throw new Error("Rank: missing argument");return`(_SYS.shape(${n(e[0])}).length)`},Shape:(e,n)=>{if(e[0]==null)throw new Error("Shape: missing argument");return`_SYS.shape(${n(e[0])})`},Flatten:(e,n)=>{let t=ve("Flatten",e[0],n);return e[1]!=null?`(${t}).flat(${n(e[1])})`:`(${t}).flat(Infinity)`},Reshape:(e,n)=>{let t=ve("Reshape",e[0],n),i=e[1];if(i==null)throw new Error("Reshape: missing shape");if(!m(i)||i.ops.length===0||i.ops.length>2)throw new Error("Reshape: only a 1-D or 2-D target shape compiles. Fail closed (D6).");return`_SYS.reshape(${t}, [${i.ops.map(r=>n(r)).join(", ")}])`},Log:(e,n)=>e.length===1?`Math.log10(${n(e[0])})`:`(Math.log(${n(e[0])}) / Math.log(${n(e[1])}))`,GammaLn:"_SYS.lngamma",Lb:"Math.log2",ElementMax:(e,n)=>`Math.max(${e.map(t=>n(t)).join(", ")})`,ElementMin:(e,n)=>`Math.min(${e.map(t=>n(t)).join(", ")})`,Clamp:(e,n)=>`Math.min(Math.max(${n(e[0])}, ${n(e[1])}), ${n(e[2])})`,Max:(e,n)=>X6("Max",e,n),Mean:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.mean(${n(e[0])})`:`_SYS.mean([${e.map(t=>n(t)).join(", ")}])`,Median:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.median(${n(e[0])})`:`_SYS.median([${e.map(t=>n(t)).join(", ")}])`,Variance:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.variance(${n(e[0])})`:`_SYS.variance([${e.map(t=>n(t)).join(", ")}])`,PopulationVariance:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.populationVariance(${n(e[0])})`:`_SYS.populationVariance([${e.map(t=>n(t)).join(", ")}])`,StandardDeviation:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.standardDeviation(${n(e[0])})`:`_SYS.standardDeviation([${e.map(t=>n(t)).join(", ")}])`,PopulationStandardDeviation:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.populationStandardDeviation(${n(e[0])})`:`_SYS.populationStandardDeviation([${e.map(t=>n(t)).join(", ")}])`,Kurtosis:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.kurtosis(${n(e[0])})`:`_SYS.kurtosis([${e.map(t=>n(t)).join(", ")}])`,Skewness:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.skewness(${n(e[0])})`:`_SYS.skewness([${e.map(t=>n(t)).join(", ")}])`,Mode:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.mode(${n(e[0])})`:`_SYS.mode([${e.map(t=>n(t)).join(", ")}])`,Quartiles:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.quartiles(${n(e[0])})`:`_SYS.quartiles([${e.map(t=>n(t)).join(", ")}])`,InterquartileRange:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.interquartileRange(${n(e[0])})`:`_SYS.interquartileRange([${e.map(t=>n(t)).join(", ")}])`,Covariance:(e,n)=>{if(e.length!==2)throw new Error("Covariance: expected two collection arguments to compile");return`_SYS.covariance(${n(e[0])}, ${n(e[1])})`},PopulationCovariance:(e,n)=>{if(e.length!==2)throw new Error("PopulationCovariance: expected two collection arguments to compile");return`_SYS.populationCovariance(${n(e[0])}, ${n(e[1])})`},Correlation:(e,n)=>{if(e.length!==2)throw new Error("Correlation: expected two collection arguments to compile");return`_SYS.correlation(${n(e[0])}, ${n(e[1])})`},Min:(e,n)=>X6("Min",e,n),Power:(e,n)=>{let t=e[0],i=e[1];if(t===null)throw new Error("Power: no argument");if(D.isComplexValued(t)||D.isComplexValued(i))return`_SYS.cpow(${n(t)}, ${n(i)})`;let r=Qe(t),o=Qe(i);if(r!==void 0&&o!==void 0){let s=Math.pow(r,o);if(Number.isNaN(s))throw new Error(`Power(${r}, ${o}) has no real value; cannot compile to a real target`);return String(s)}if(o===0)return"1";if(o===1)return n(t);if(o===2&&(w(t)||N(t))){let s=n(t);return`(${s} * ${s})`}return o===-1?`(1 / (${n(t)}))`:o===.5?`Math.sqrt(${n(t)})`:o===1/3?`Math.cbrt(${n(t)})`:o===-.5?`(1 / Math.sqrt(${n(t)}))`:o===void 0?`_SYS.pow(${n(t)}, ${n(i)})`:`Math.pow(${n(t)}, ${n(i)})`},Range:(e,n)=>{if(e.length===0)return"[]";if(e.length===1)return`Array.from({length: ${n(e[0])}}, (_, i) => i)`;let t=n(e[0]),i=n(e[1]),r=e[2]?n(e[2]):"1";if(t===null)throw new Error("Range: no start");if(i===null&&(i=t,t="1"),r==="0")throw new Error("Range: step cannot be zero");if(e[2]===void 0||e[2]===null){let o=parseFloat(i),s=parseFloat(t);if(!isNaN(o)&&!isNaN(s)){let a=o>=s?1:-1,u=Math.floor(Math.abs(o-s))+1;return u<50?`[${Array.from({length:u},(l,c)=>s+a*c).join(", ")}]`:`Array.from({length: ${u}}, (_e, i) => ${t} ${a===1?"+":"-"} i)`}return`((_a, _b) => Array.from({length: Math.floor(Math.abs(_b - _a)) + 1}, (_e, _i) => _b >= _a ? _a + _i : _a - _i))(${t}, ${i})`}return`Array.from({length: Math.floor((${i} - ${t}) / ${r}) + 1}, (_e, i) => ${t} + i * ${r})`},Root:([e,n],t)=>{if(e===null)throw new Error("Root: no argument");if(n===null)return`Math.sqrt(${t(e)})`;let i=Qe(e),r=Qe(n);if(i!==void 0&&r!==void 0&&r!==0){let o=Math.pow(i,1/r);if(Number.isNaN(o)){if(Number.isInteger(r)&&r%2!==0&&i<0)return String(-Math.pow(-i,1/r));throw new Error(`Root(${i}, ${r}) has no real value; cannot compile to a real target`)}return String(o)}return r===2?`Math.sqrt(${t(e)})`:r===3?`Math.cbrt(${t(e)})`:r!==void 0&&Number.isInteger(r)&&r%2!==0?D.inlineExpression(`(Math.sign(\${x}) * Math.pow(Math.abs(\${x}), ${1/r}))`,t(e)):r!==void 0?`Math.pow(${t(e)}, ${1/r})`:`Math.pow(${t(e)}, 1 / (${t(n)}))`},Random:(e,n,t)=>{let i=t?.randomSeed,r=e.length===1&&!D.isIntegerValued(e[0]);if(i!=null&&!r){let a=t?.randomState?t.randomState.counter++:0,u=dp((i^Math.imul(a+1,2654435761))>>>0)();if(e.length===0)return u.toString();if(e.length===2){let l=n(e[0]),c=n(e[1]);return`((${l}) + Math.floor(${u} * ((${c}) - (${l}))))`}return`Math.floor(${u} * (${n(e[0])}))`}if(e.length===0)return"Math.random()";if(e.length===2){let a=n(e[0]),u=n(e[1]);return`((${a}) + Math.floor(Math.random() * ((${u}) - (${a}))))`}let o=e[0];return D.isIntegerValued(o)?`Math.floor(Math.random() * (${n(o)}))`:`(() => { const _s = (${n(o)}) * 12.9898; const _v = Math.sin(_s) * 43758.5453; return _v - Math.floor(_v); })()`},Round:(e,n)=>{if(e.length<2)return D.isIntegerValued(e[0])?n(e[0]):D.inlineExpression("(Math.sign(${x}) * Math.round(Math.abs(${x})))",n(e[0]));let t=D.tempVar(),i=D.tempVar();return`(() => { const ${i} = Math.pow(10, ${n(e[1])}); const ${t} = ${n(e[0])} * ${i}; return (Math.sign(${t}) * Math.round(Math.abs(${t}))) / ${i}; })()`},Square:(e,n)=>{let t=e[0];if(t===null)throw new Error("Square: no argument");let i=Qe(t);if(i!==void 0)return String(i*i);if(w(t)){let r=n(t);return`(${r} * ${r})`}return`Math.pow(${n(t)}, 2)`},Sec:(e,n)=>{let t=e[0];if(t===null)throw new Error("Sec: no argument");return D.isComplexValued(t)?`_SYS.csec(${n(t)})`:`1 / Math.cos(${n(t)})`},Sech:(e,n)=>{let t=e[0];if(t===null)throw new Error("Sech: no argument");return D.isComplexValued(t)?`_SYS.csech(${n(t)})`:`1 / Math.cosh(${n(t)})`},Second:(e,n)=>`${n(e[0])}[1]`,Heaviside:"_SYS.heaviside",Sign:"Math.sign",Sinc:"_SYS.sinc",FresnelS:"_SYS.fresnelS",FresnelC:"_SYS.fresnelC",Sin:(e,n)=>D.isComplexValued(e[0])?`_SYS.csin(${n(e[0])})`:`Math.sin(${n(e[0])})`,Sinh:(e,n)=>D.isComplexValued(e[0])?`_SYS.csinh(${n(e[0])})`:`Math.sinh(${n(e[0])})`,Sqrt:(e,n)=>{if(D.isComplexValued(e[0]))return`_SYS.csqrt(${n(e[0])})`;let t=Qe(e[0]);if(t!==void 0){let i=Math.sqrt(t);if(Number.isNaN(i))throw new Error(`Sqrt(${t}) has no real value; cannot compile to a real target`);return String(i)}return`Math.sqrt(${n(e[0])})`},Tan:(e,n)=>D.isComplexValued(e[0])?`_SYS.ctan(${n(e[0])})`:`Math.tan(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`_SYS.ctanh(${n(e[0])})`:`Math.tanh(${n(e[0])})`,Third:(e,n)=>`${n(e[0])}[2]`,PointX:(e,n)=>_S(e[0],0,n),PointY:(e,n)=>_S(e[0],1,n),PointZ:(e,n)=>_S(e[0],2,n),Mod:([e,n],t)=>{if(e===null||n===null)throw new Error("Mod: missing argument");let i=t(e),r=t(n);return D.isIntegerValued(e)&&D.isIntegerValued(n)&&D.isNonNegative(e)?`(${i} % ${r})`:`(((${i} % ${r}) + ${r}) % ${r})`},Truncate:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.trunc(${n(e[0])})`,Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");return`(${t(e)} - ${t(n)} * Math.round(${t(e)} / ${t(n)}))`},Divide:([e,n],t)=>{if(e===null||n===null)throw new Error("Divide: missing argument");let i=D.isComplexValued(e),r=D.isComplexValued(n);if(!i&&!r){let o=Qe(e),s=Qe(n);return o!==void 0&&s!==void 0&&s!==0?String(o/s):s===1?t(e):`(${t(e)} / ${t(n)})`}return i&&r?`(() => { const _a = ${t(e)}, _b = ${t(n)}, _d = _b.re * _b.re + _b.im * _b.im; return { re: (_a.re * _b.re + _a.im * _b.im) / _d, im: (_a.im * _b.re - _a.re * _b.im) / _d }; })()`:i&&!r?`(() => { const _a = ${t(e)}, _r = ${t(n)}; return { re: _a.re / _r, im: _a.im / _r }; })()`:`(() => { const _r = ${t(e)}, _b = ${t(n)}, _d = _b.re * _b.re + _b.im * _b.im; return { re: _r * _b.re / _d, im: -_r * _b.im / _d }; })()`},Negate:([e],n)=>{if(e===null)throw new Error("Negate: no argument");if(!D.isComplexValued(e)){let t=Qe(e);return t!==void 0?String(-t):`(-${n(e)})`}return`_SYS.cneg(${n(e)})`},Multiply:(e,n)=>{if(e.length===1)return n(e[0]);if(!e.some(s=>D.isComplexValued(s))){if(e.some(u=>Qe(u)===0))return"0";let s=e.map(Qe);if(s.every(u=>u!==void 0))return String(s.reduce((u,l)=>u*l,1));let a=e.filter(u=>Qe(u)!==1);return a.length===0?"1":a.length===1?n(a[0]):`(${a.map(u=>n(u)).join(" * ")})`}if(e.length===2){let s=D.isComplexValued(e[0]),a=D.isComplexValued(e[1]),u=n(e[0]),l=n(e[1]);return s&&a?`(() => { const _a = ${u}, _b = ${l}; return { re: _a.re * _b.re - _a.im * _b.im, im: _a.re * _b.im + _a.im * _b.re }; })()`:s&&!a?`(() => { const _a = ${u}, _r = ${l}; return { re: _a.re * _r, im: _a.im * _r }; })()`:`(() => { const _r = ${u}, _b = ${l}; return { re: _r * _b.re, im: _r * _b.im }; })()`}let i=[],r=[];for(let s=0;s<e.length;s++){let a=`_v${s}`;r.push(a),i.push(`const ${a} = ${n(e[s])}`)}let o=D.isComplexValued(e[0]);i.push(`let _re = ${o?`${r[0]}.re`:r[0]}`),i.push(`let _im = ${o?`${r[0]}.im`:"0"}`);for(let s=1;s<e.length;s++){let a=r[s],u=D.isComplexValued(e[s]),l=u?`${a}.re`:a,c=u?`${a}.im`:"0";i.push(`const _nre${s} = _re * ${l} - _im * ${c}`),i.push(`const _nim${s} = _re * ${c} + _im * ${l}`),i.push(`_re = _nre${s}`),i.push(`_im = _nim${s}`)}return`(() => { ${i.join("; ")}; return { re: _re, im: _im }; })()`},Factorial:"_SYS.factorial",Factorial2:"_SYS.factorial2",Exp2:([e],n)=>{if(e===null)throw new Error("Exp2: no argument");return`Math.pow(2, ${n(e)})`},Log2:"Math.log2",Log10:"Math.log10",Lg:"Math.log10",Arctan2:"Math.atan2",Hypot:"Math.hypot",Degrees:([e],n)=>{if(e===null)throw new Error("Degrees: no argument");return`(${n(e)} * Math.PI / 180)`},Haversine:([e],n)=>{if(e===null)throw new Error("Haversine: no argument");return D.inlineExpression("(1 - Math.cos(${x})) / 2",n(e))},InverseHaversine:([e],n)=>{if(e===null)throw new Error("InverseHaversine: no argument");return`(2 * Math.asin(Math.sqrt(${n(e)})))`},Erf:"_SYS.erf",Erfc:"_SYS.erfc",ErfInv:"_SYS.erfInv",Erfi:"_SYS.erfi",Beta:"_SYS.beta",GammaRegularized:"_SYS.gammaQ",BetaRegularized:"_SYS.betaRegularized",Digamma:"_SYS.digamma",Trigamma:"_SYS.trigamma",PolyGamma:(e,n)=>`_SYS.polygamma(${n(e[0])}, ${n(e[1])})`,Zeta:"_SYS.zeta",LambertW:"_SYS.lambertW",BesselJ:(e,n)=>`_SYS.besselJ(${n(e[0])}, ${n(e[1])})`,BesselY:(e,n)=>`_SYS.besselY(${n(e[0])}, ${n(e[1])})`,BesselI:(e,n)=>`_SYS.besselI(${n(e[0])}, ${n(e[1])})`,BesselK:(e,n)=>`_SYS.besselK(${n(e[0])}, ${n(e[1])})`,AiryAi:"_SYS.airyAi",AiryBi:"_SYS.airyBi",AiryAiPrime:"_SYS.airyAiPrime",AiryBiPrime:"_SYS.airyBiPrime",SinIntegral:"_SYS.sinIntegral",CosIntegral:"_SYS.cosIntegral",ExpIntegralEi:"_SYS.expIntegralEi",LogIntegral:"_SYS.logIntegral",AGM:(e,n)=>e.length===1?`_SYS.agm(1, ${n(e[0])})`:`_SYS.agm(${n(e[0])}, ${n(e[1])})`,EllipticK:"_SYS.ellipticK",EllipticE:(e,n)=>e.length===2?`_SYS.ellipticEIncomplete(${n(e[0])}, ${n(e[1])})`:`_SYS.ellipticE(${n(e[0])})`,EllipticF:(e,n)=>`_SYS.ellipticF(${n(e[0])}, ${n(e[1])})`,EllipticPi:(e,n)=>e.length===3?`_SYS.ellipticPiIncomplete(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.ellipticPiComplete(${n(e[0])}, ${n(e[1])})`,Hypergeometric2F1:(e,n)=>`_SYS.hypergeometric2F1(${n(e[0])}, ${n(e[1])}, ${n(e[2])}, ${n(e[3])})`,Hypergeometric1F1:(e,n)=>`_SYS.hypergeometric1F1(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`,Mandelbrot:([e,n],t)=>{if(e===null||n===null)throw new Error("Mandelbrot: missing arguments");return`_SYS.mandelbrot(${t(e)}, ${t(n)})`},Julia:([e,n,t],i)=>{if(e===null||n===null||t===null)throw new Error("Julia: missing arguments");return`_SYS.julia(${i(e)}, ${i(n)}, ${i(t)})`},Binomial:(e,n)=>`_SYS.binomial(${n(e[0])}, ${n(e[1])})`,Choose:(e,n)=>`_SYS.binomial(${n(e[0])}, ${n(e[1])})`,Fibonacci:"_SYS.fibonacci",Real:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).re`:n(e[0]),Imaginary:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).im`:"0",Argument:(e,n)=>D.isComplexValued(e[0])?`_SYS.carg(${n(e[0])})`:`(${n(e[0])} >= 0 ? 0 : Math.PI)`,Conjugate:(e,n)=>D.isComplexValued(e[0])?`_SYS.cconj(${n(e[0])})`:n(e[0]),Color:([e],n)=>{if(e===null)throw new Error("Color: no argument");return`_SYS.color(${n(e)})`},ColorToString:(e,n)=>{if(e.length===0)throw new Error("ColorToString: no argument");return e.length>=2?`_SYS.colorToString(${n(e[0])}, ${n(e[1])})`:`_SYS.colorToString(${n(e[0])})`},ColorMix:(e,n)=>{if(e.length<2)throw new Error("ColorMix: need two colors");return e.length>=3?`_SYS.colorMix(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.colorMix(${n(e[0])}, ${n(e[1])})`},ColorContrast:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorContrast: need two colors");return`_SYS.colorContrast(${t(e)}, ${t(n)})`},ContrastingColor:(e,n)=>{if(e.length===0)throw new Error("ContrastingColor: no argument");return e.length>=3?`_SYS.contrastingColor(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.contrastingColor(${n(e[0])})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");return`_SYS.colorToColorspace(${t(e)}, ${t(n)})`},ColorFromColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorFromColorspace: need components and space");return`_SYS.colorFromColorspace(${t(e)}, ${t(n)})`},Colormap:(e,n)=>{if(e.length===0)throw new Error("Colormap: no argument");return e.length>=2?`_SYS.colormap(${n(e[0])}, ${n(e[1])})`:`_SYS.colormap(${n(e[0])})`},Rgb:(e,n)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_SYS.rgb(${e.map(n).join(", ")})`},Hsv:(e,n)=>{if(e.length<3)throw new Error("Hsv: need 3 components");return`_SYS.hsv(${e.map(n).join(", ")})`},Hsl:(e,n)=>{if(e.length<3)throw new Error("Hsl: need 3 components");return`_SYS.hsl(${e.map(n).join(", ")})`},Oklab:(e,n)=>{if(e.length<3)throw new Error("Oklab: need 3 components");return`_SYS.oklab(${e.map(n).join(", ")})`},Oklch:(e,n)=>{if(e.length<3)throw new Error("Oklch: need 3 components");return`_SYS.oklch(${e.map(n).join(", ")})`},AsRgb:([e],n)=>{if(e===null)throw new Error("AsRgb: no argument");return`_SYS.asRgb(${n(e)})`},AsHsv:([e],n)=>{if(e===null)throw new Error("AsHsv: no argument");return`_SYS.asHsv(${n(e)})`},AsHsl:([e],n)=>{if(e===null)throw new Error("AsHsl: no argument");return`_SYS.asHsl(${n(e)})`},AsOklab:([e],n)=>{if(e===null)throw new Error("AsOklab: no argument");return`_SYS.asOklab(${n(e)})`},AsOklch:([e],n)=>{if(e===null)throw new Error("AsOklch: no argument");return n(e)},ColorDelta:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorDelta: need two colors");return`_SYS.colorDelta(${t(e)}, ${t(n)})`},Distance:([e,n],t)=>{if(e===null||n===null)throw new Error("Distance: need two points");return`_SYS.distance(${t(e)}, ${t(n)})`}};function dn(e){return{re:e.re,im:e.im}}function br(e){if(e!==void 0&&Number.isFinite(e)&&!(Math.abs(e-1)<1e-9))return e}function mo(e){if(typeof e=="string"){let t=Pt(e),i={r:t>>>24&255,g:t>>>16&255,b:t>>>8&255},r=br((t&255)/255);return r!==void 0&&(i.alpha=r),i}let n=Hs({L:e[0],C:e[1],H:e[2]});if(e.length>=4){let t=br(e[3]);t!==void 0&&(n.alpha=t)}return n}function hd(e){if(typeof e=="string"){let n=Pt(e),t=n>>>24&255,i=n>>>16&255,r=n>>>8&255,o=Pn({r:t,g:i,b:r}),s=br((n&255)/255);return s!==void 0&&(o.alpha=s),o}return{L:e[0],C:e[1],H:e[2],alpha:e.length>=4?br(e[3]):void 0}}function Vb(e){let n=e>>>24&255,t=e>>>16&255,i=e>>>8&255,r=Pn({r:n,g:t,b:i}),o=br((e&255)/255);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]}var RY={color(e){return Vb(Pt(e))},colorToString(e,n){let t=mo(e),i=(n??"hex").toLowerCase();switch(i){case"hex":{let r=Math.round(Math.max(0,Math.min(255,t.r))),o=Math.round(Math.max(0,Math.min(255,t.g))),s=Math.round(Math.max(0,Math.min(255,t.b))),a=`#${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;if(t.alpha!==void 0){let u=Math.round(Math.max(0,Math.min(255,t.alpha*255)));a+=u.toString(16).padStart(2,"0")}return a}case"rgb":{let r=Math.round(t.r),o=Math.round(t.g),s=Math.round(t.b);return t.alpha!==void 0?`rgb(${r} ${o} ${s} / ${t.alpha})`:`rgb(${r} ${o} ${s})`}case"hsl":{let r=Us(t.r,t.g,t.b),o=Math.round(r.h*10)/10,s=Math.round(r.s*1e3)/10,a=Math.round(r.l*1e3)/10;return t.alpha!==void 0?`hsl(${o} ${s}% ${a}% / ${t.alpha})`:`hsl(${o} ${s}% ${a}%)`}case"oklch":{let r=Pn(t),o=Math.round(r.L*1e3)/1e3,s=Math.round(r.C*1e3)/1e3,a=Math.round(r.H*10)/10;return t.alpha!==void 0?`oklch(${o} ${s} ${a} / ${t.alpha})`:`oklch(${o} ${s} ${a})`}default:throw new Error(`Unknown color format: ${i}`)}},colorMix(e,n,t=.5){let i=hd(e),r=hd(n);t=Math.max(0,Math.min(1,t));let o=i.C<1e-6,s=r.C<1e-6,a;if(o&&s)a=i.H;else if(o)a=r.H;else if(s)a=i.H;else{let d=r.H-i.H;d>180&&(d-=360),d<-180&&(d+=360),a=i.H+d*t,a<0&&(a+=360),a>=360&&(a-=360)}let u=i.L+(r.L-i.L)*t,l=i.C+(r.C-i.C)*t,c=i.alpha??1,f=r.alpha??1,p=br(c+(f-c)*t);return p!==void 0?[u,l,a,p]:[u,l,a]},colorContrast(e,n){return Kl(mo(e),mo(n))},contrastingColor(e,n,t){let i=mo(e);return Vb(n!==void 0&&t!==void 0?nc({bg:i,fg1:mo(n),fg2:mo(t)}):nc(i))},colorToColorspace(e,n){let t=mo(e),i=t.alpha,r;switch(n.toLowerCase()){case"rgb":r=[t.r/255,t.g/255,t.b/255];break;case"hsl":{let o=Us(t.r,t.g,t.b);r=[o.h,o.s,o.l];break}case"oklch":{let o=Pn(t);r=[o.L,o.C,o.H];break}case"oklab":case"lab":{let o=ec(t);r=[o.L,o.a,o.b];break}default:throw new Error(`Unknown color space: ${n}`)}return i!==void 0&&r.push(i),r},colormap(e,n){let i={...eb,...Kh,...Xh}[e];if(!i)throw new Error(`Unknown palette: ${e}`);let r=i.map(s=>Vb(Pt(s)));if(n===void 0)return r;if(Number.isInteger(n)&&n>=2){let s=n,a=[];for(let u=0;u<s;u++){let l=s===1?0:u/(s-1);a.push(this._interpolatePalette(r,l))}return a}let o=Math.max(0,Math.min(1,n));return this._interpolatePalette(r,o)},_interpolatePalette(e,n){if(e.length===0)return[0,0,0];if(n<=0)return[...e[0]];if(n>=1)return[...e[e.length-1]];let t=n*(e.length-1),i=Math.floor(t),r=t-i;if(r===0||i>=e.length-1)return[...e[Math.min(i,e.length-1)]];let[o,s,a]=e[i],[u,l,c]=e[i+1],f=s<1e-6,p=l<1e-6,d;if(f&&p)d=a;else if(f)d=c;else if(p)d=a;else{let g=c-a;g>180&&(g-=360),g<-180&&(g+=360),d=a+g*r,d<0&&(d+=360),d>=360&&(d-=360)}return[o+(u-o)*r,s+(l-s)*r,d]},colorFromColorspace(e,n){let t=e[0],i=e[1],r=e[2],o=e.length>=4?e[3]:void 0,s;switch(n.toLowerCase()){case"rgb":s=Pn({r:t*255,g:i*255,b:r*255});break;case"hsl":{let a=Gs(t,i,r);s=Pn(a);break}case"oklch":s={L:t,C:i,H:r};break;case"oklab":case"lab":s=Zs({L:t,a:i,b:r});break;default:throw new Error(`Unknown color space: ${n}`)}return o!==void 0?[s.L,s.C,s.H,o]:[s.L,s.C,s.H]},rgb(e,n,t,i){let r=Pn({r:e*255,g:n*255,b:t*255}),o=br(i);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]},hsv(e,n,t,i){let r=Hp(e,n,t),o=Pn(r),s=br(i);return s!==void 0?[o.L,o.C,o.H,s]:[o.L,o.C,o.H]},hsl(e,n,t,i){let r=Gs(e,n,t),o=Pn({r:r.r,g:r.g,b:r.b}),s=br(i);return s!==void 0?[o.L,o.C,o.H,s]:[o.L,o.C,o.H]},oklab(e,n,t,i){let r=Zs({L:e,a:n,b:t}),o=br(i);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]},oklch(e,n,t,i){let r=br(i);return r!==void 0?[e,n,t,r]:[e,n,t]},asRgb(e){let n=mo(e),t=n.r/255,i=n.g/255,r=n.b/255;return n.alpha!==void 0?[t,i,r,n.alpha]:[t,i,r]},asHsv(e){let n=mo(e),t=Wh(n.r,n.g,n.b);return n.alpha!==void 0?[t.h,t.s,t.v,n.alpha]:[t.h,t.s,t.v]},asHsl(e){let n=mo(e),t=Us(n.r,n.g,n.b);return n.alpha!==void 0?[t.h,t.s,t.l,n.alpha]:[t.h,t.s,t.l]},asOklab(e){let n=hd(e),t=Zi({L:n.L,C:n.C,H:n.H});return n.alpha!==void 0?[t.L,t.a,t.b,n.alpha]:[t.L,t.a,t.b]},colorDelta(e,n){let t=Zi(hd(e)),i=Zi(hd(n));return Qh(t,i)},distance(e,n){if(!Array.isArray(e)||!Array.isArray(n))throw new Error("Distance: expected two arrays");if(e.length!==n.length)throw new Error("Distance: dimension mismatch");let t=0;for(let i=0;i<e.length;i++){let r=e[i]-n[i];t+=r*r}return Math.sqrt(t)}};function Jb(e,...n){let t=-1;for(let r of n)Array.isArray(r)&&(t=t<0?r.length:Math.min(t,r.length));if(t<0)return e(...n);let i=new Array(t);for(let r=0;r<t;r++)i[r]=Jb(e,...n.map(o=>Array.isArray(o)?o[r]:o));return i}function CS(e,n){let t=Array.isArray(e?.[0]),i=Array.isArray(n?.[0]);if(!t&&!i){if(e.length!==n.length)return NaN;let u=0;for(let l=0;l<e.length;l++)u+=e[l]*n[l];return u}if(t&&!i)return e.map(u=>u.length===n.length?u.reduce((l,c,f)=>l+c*n[f],0):NaN);if(!t&&i){if(e.length!==n.length)return NaN;let u=n[0].length,l=new Array(u).fill(0);for(let c=0;c<e.length;c++)for(let f=0;f<u;f++)l[f]+=e[c]*n[c][f];return l}let r=e.length,o=e[0].length;if(n.length!==o)return NaN;let s=n[0].length,a=[];for(let u=0;u<r;u++){let l=new Array(s).fill(0);for(let c=0;c<o;c++){let f=e[u][c];for(let p=0;p<s;p++)l[p]+=f*n[c][p]}a.push(l)}return a}function PY(...e){let n=[],t=1;for(let r of e)Array.isArray(r)?n.push(r):t*=r;if(n.length===0)return t;let i=n[0];for(let r=1;r<n.length;r++){let o=n[r],s=!Array.isArray(i[0]),a=!Array.isArray(o[0]);if(s&&a){if(i.length!==o.length)return NaN;let u=new Array(i.length);for(let l=0;l<i.length;l++)u[l]=i[l]*o[l];i=u}else{let u=CS(i,o);if(typeof u=="number")return u;i=u}}return t!==1&&(i=Jb(r=>r*t,i)),i}function gc(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);if(i&&r){if(e.length!==n.length)return!1;for(let u=0;u<e.length;u++)if(gc(e[u],n[u],t)!==!0)return!1;return!0}if(i)return e.map(u=>gc(u,n,t));if(r)return n.map(u=>gc(e,u,t));let o=u=>typeof u=="object"&&u!==null&&"re"in u?u:{re:u,im:0},s=o(e),a=o(n);return Math.hypot(s.re-a.re,s.im-a.im)<=t}function IS(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);return i&&r?gc(e,n,t)!==!0:i?e.map(o=>IS(o,n,t)):r?n.map(o=>IS(e,o,t)):gc(e,n,t)!==!0}function iO(e){let n=e?.length;if(!n||e.some(i=>!Array.isArray(i)||i.length!==n))return NaN;let t=e.map((i,r)=>[...i,...Array.from({length:n},(o,s)=>r===s?1:0)]);for(let i=0;i<n;i++){let r=i;for(let s=i+1;s<n;s++)Math.abs(t[s][i])>Math.abs(t[r][i])&&(r=s);if(t[r][i]===0)return NaN;r!==i&&([t[i],t[r]]=[t[r],t[i]]);let o=t[i][i];for(let s=0;s<2*n;s++)t[i][s]/=o;for(let s=0;s<n;s++){if(s===i)continue;let a=t[s][i];if(a!==0)for(let u=0;u<2*n;u++)t[s][u]-=a*t[i][u]}}return t.map(i=>i.slice(n))}function DY(e){let n=t=>t&&typeof t=="object"&&"im"in t?{re:t.re,im:-t.im}:t;return Array.isArray(e)?Array.isArray(e[0])?e[0].map((t,i)=>e.map(r=>n(r[i]))):e.map(n):e}function OY(e){if(!Array.isArray(e))return NaN;if(Array.isArray(e[0])){let t=Math.min(e.length,e[0].length),i=[];for(let r=0;r<t;r++)i.push(e[r][r]);return i}let n=e.length;return Array.from({length:n},(t,i)=>Array.from({length:n},(r,o)=>i===o?e[i]:0))}function LY(e,n){if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let t=e.length;if(e.some(s=>!Array.isArray(s)||s.length!==t))return NaN;if(!Number.isInteger(n))return NaN;let i=e.map(s=>s.slice()),r=n;if(r<0){let s=iO(e);if(!Array.isArray(s))return NaN;i=s,r=-r}let o=Array.from({length:t},(s,a)=>Array.from({length:t},(u,l)=>a===l?1:0));for(let s=0;s<r;s++)o=CS(o,i);return o}function FY(e){if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let n=e.length,t=e[0].length,i=e.map(o=>o.slice()),r=0;for(let o=0;o<t&&r<n;o++){let s=r;for(let u=r+1;u<n;u++)Math.abs(i[u][o])>Math.abs(i[s][o])&&(s=u);if(i[s][o]===0)continue;s!==r&&([i[s],i[r]]=[i[r],i[s]]);let a=i[r][o];for(let u=0;u<t;u++)i[r][u]/=a;for(let u=0;u<n;u++){if(u===r)continue;let l=i[u][o];if(l!==0)for(let c=0;c<t;c++)i[u][c]-=l*i[r][c]}r++}return i}var rO={bcast:Jb,add:(e,n)=>Jb((t,i)=>t+i,e,n),chop:Jc,factorial:Vc,factorial2:ga,gamma:Me,gcd:qc,pow:(e,n)=>e===0&&n===0?NaN:Math.pow(e,n),cond:e=>{if(e===!0||e===!1)return e;throw new Error('Condition must evaluate to "True" or "False".')},heaviside:e=>e<0?0:e===0?.5:1,shuffle:(e,n)=>{let t=n===void 0?Math.random:dp(n>>>0),i=e.slice();for(let r=i.length-1;r>0;r--){let o=Math.floor(t()*(r+1));[i[r],i[o]]=[i[o],i[r]]}return i},matmul:CS,mul:PY,eq:gc,neq:IS,cross:(e,n)=>e.length===3&&n.length===3?[e[1]*n[2]-e[2]*n[1],e[2]*n[0]-e[0]*n[2],e[0]*n[1]-e[1]*n[0]]:NaN,norm:(e,n)=>{if(typeof e=="number")return Math.abs(e);if(!Array.isArray(e))return NaN;if(Array.isArray(e[0])&&n!==void 0){let r=e;if(n===1){let o=0;for(let s=0;s<r[0].length;s++){let a=0;for(let u=0;u<r.length;u++)a+=Math.abs(r[u][s]);o=Math.max(o,a)}return o}if(n===1/0){let o=0;for(let s of r){let a=0;for(let u of s)a+=Math.abs(u);o=Math.max(o,a)}return o}return NaN}let t=e.flat(1/0);if(n===1/0){let r=0;for(let o of t)r=Math.max(r,Math.abs(o));return r}if(n===void 0||n===2){let r=0;for(let o of t)r+=o*o;return Math.sqrt(r)}let i=0;for(let r of t)i+=Math.pow(Math.abs(r),n);return Math.pow(i,1/n)},transpose:e=>!Array.isArray(e)||!Array.isArray(e[0])?e:e[0].map((n,t)=>e.map(i=>i[t])),det:e=>{let n=e?.length;if(!n||e.some(r=>!Array.isArray(r)||r.length!==n))return NaN;let t=e.map(r=>r.slice()),i=1;for(let r=0;r<n;r++){let o=r;for(let s=r+1;s<n;s++)Math.abs(t[s][r])>Math.abs(t[o][r])&&(o=s);if(t[o][r]===0)return 0;o!==r&&([t[r],t[o]]=[t[o],t[r]],i=-i),i*=t[r][r];for(let s=r+1;s<n;s++){let a=t[s][r]/t[r][r];for(let u=r;u<n;u++)t[s][u]-=a*t[r][u]}}return i},inv:iO,conjTranspose:DY,diagonal:OY,matpow:LY,rref:FY,trace:e=>{if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let n=0;for(let t=0;t<Math.min(e.length,e[0].length);t++){if(typeof e[t][t]!="number")return NaN;n+=e[t][t]}return n},shape:e=>{let n=[],t=e;for(;Array.isArray(t);)n.push(t.length),t=t[0];return n},reshape:(e,n)=>{let t=e.flat(1/0);if(t.length===0)return NaN;let i=r=>t[r%t.length];return n.length===1?Array.from({length:Math.max(0,n[0])},(r,o)=>i(o)):n.length===2?Array.from({length:Math.max(0,n[0])},(r,o)=>Array.from({length:Math.max(0,n[1])},(s,a)=>i(o*n[1]+a))):NaN},at:(e,n)=>{if(!Array.isArray(e))return NaN;let t=e.length,i=n>0?n-1:t+n;return n===0||i<0||i>=t?NaN:e[i]},integrate:(e,n,t)=>{let i=Ya(e,n,t);return i.converged?i.estimate:jl(e,n,t,1e7).estimate},integrateMC:(e,n,t)=>jl(e,n,t,1e7).estimate,lcm:Ud,lngamma:Nn,limit:wo,mean:hb,median:ou,variance:rc,populationVariance:oc,standardDeviation:LD,populationStandardDeviation:FD,kurtosis:bb,skewness:yb,mode:xb,quartiles:ad,interquartileRange:_b,covariance:Eb,populationCovariance:vb,correlation:Sb,erf:Zo,erfc:Uo,erfInv:xl,beta:ng,gammaQ:bl,betaRegularized:yl,digamma:El,trigamma:vl,polygamma:eg,zeta:Vr,lambertW:tg,besselJ:qr,besselY:gl,besselI:zo,besselK:ig,airyAi:ag,airyBi:ug,airyAiPrime:lg,airyBiPrime:cg,sinc:fg,fresnelS:Jr,fresnelC:jr,sinIntegral:gg,cosIntegral:hg,expIntegralEi:Go,logIntegral:bg,erfi:dg,agm:Xf,ellipticK:ep,ellipticE:np,ellipticEIncomplete:rp,ellipticF:ip,ellipticPiComplete:op,ellipticPiIncomplete:sp,hypergeometric2F1:ap,hypergeometric1F1:up,mandelbrot:(e,n)=>{let t=0,i=0,r=typeof e=="number"?e:e.re,o=typeof e=="number"?0:e.im,s=Math.round(n);for(let a=0;a<s;a++){let u=t*t-i*i+r;i=2*t*i+o,t=u;let l=t*t+i*i;if(l>4){let c=(a-Math.log2(Math.log2(l))+4)/s;return Math.max(0,Math.min(1,c))}}return 1},julia:(e,n,t)=>{let i=typeof e=="number"?e:e.re,r=typeof e=="number"?0:e.im,o=typeof n=="number"?n:n.re,s=typeof n=="number"?0:n.im,a=Math.round(t);for(let u=0;u<a;u++){let l=i*i-r*r+o;r=2*i*r+s,i=l;let c=i*i+r*r;if(c>4){let f=(u-Math.log2(Math.log2(c))+4)/a;return Math.max(0,Math.min(1,f))}}return 1},binomial:cl,fibonacci:MS,csin:e=>dn(new L(e.re,e.im).sin()),ccos:e=>dn(new L(e.re,e.im).cos()),ctan:e=>dn(new L(e.re,e.im).tan()),casin:e=>dn(new L(e.re,e.im).asin()),cacos:e=>dn(new L(e.re,e.im).acos()),catan:e=>dn(new L(e.re,e.im).atan()),csinh:e=>dn(new L(e.re,e.im).sinh()),ccosh:e=>dn(new L(e.re,e.im).cosh()),ctanh:e=>dn(new L(e.re,e.im).tanh()),csqrt:e=>dn(new L(e.re,e.im).sqrt()),cexp:e=>dn(new L(e.re,e.im).exp()),cln:e=>dn(new L(e.re,e.im).log()),cpow:(e,n)=>{let t=typeof e=="number"?new L(e,0):new L(e.re,e.im),i=typeof n=="number"?new L(n,0):new L(n.re,n.im);return dn(t.pow(i))},ccot:e=>dn(new L(e.re,e.im).cot()),csec:e=>dn(new L(e.re,e.im).sec()),ccsc:e=>dn(new L(e.re,e.im).csc()),ccoth:e=>dn(new L(e.re,e.im).coth()),csech:e=>dn(new L(e.re,e.im).sech()),ccsch:e=>dn(new L(e.re,e.im).csch()),cacot:e=>dn(new L(e.re,e.im).acot()),casec:e=>dn(new L(e.re,e.im).asec()),cacsc:e=>dn(new L(e.re,e.im).acsc()),cacoth:e=>dn(new L(e.re,e.im).acoth()),casech:e=>dn(new L(e.re,e.im).asech()),cacsch:e=>dn(new L(e.re,e.im).acsch()),cabs:e=>new L(e.re,e.im).abs(),carg:e=>new L(e.re,e.im).arg(),cconj:e=>dn(new L(e.re,e.im).conjugate()),cneg:e=>({re:-e.re,im:-e.im}),...RY},TS=class extends Function{SYS=rO;constructor(n,t=""){return super("_SYS","_",t?`${t};return ${n}`:`return ${n}`),new Proxy(this,{apply:(i,r,o)=>super.apply(r,[this.SYS,...o]),get:(i,r)=>r==="toString"?()=>n:r==="isCompiled"?!0:Reflect.get(i,r)})}},jb=class extends Function{SYS=rO;constructor(n,t,i=""){return super("_SYS",...t,i?`${i}return ${n}`:`return ${n}`),new Proxy(this,{apply:(r,o,s)=>super.apply(o,[this.SYS,...s]),get:(r,o)=>o==="toString"?()=>i?`(${t.join(", ")}) => { ${i}return ${n}; }`:`(${t.join(", ")}) => ${n}`:o==="isCompiled"?!0:Reflect.get(r,o)})}},hc=class{getOperators(){return SS}getFunctions(){return NS}createTarget(n={}){return{language:"javascript",operators:t=>SS[t],functions:t=>NS[t],var:t=>({Pi:"Math.PI",ExponentialE:"Math.E",NaN:"Number.NaN",ImaginaryUnit:"({ re: 0, im: 1 })",Half:"0.5",MachineEpsilon:"Number.EPSILON",GoldenRatio:"((1 + Math.sqrt(5)) / 2)",CatalanConstant:"0.91596559417721901",EulerGamma:"0.57721566490153286"})[t],string:t=>JSON.stringify(t),number:t=>t.toString(),complex:(t,i)=>`({ re: ${t}, im: ${i} })`,bindExpr:(t,i)=>`((${t.map(r=>r[0]).join(", ")}) => ${i})(${t.map(r=>r[1]).join(", ")})`,assertBoolean:t=>`_SYS.cond(${t})`,indent:0,ws:t=>t??"",preamble:"",...n}}compile(n,t={}){try{return this.compileOrThrow(n,t)}catch(i){if(t.fallback!==!0)throw i;let r=i.message;return console.warn(`Compilation fallback for "${n.operator}" (target: javascript): ${r}`),D.buildInterpreterFallback(n,r,"javascript",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=po(n);let{operators:i,functions:r,vars:o,imports:s=[],preamble:a,realOnly:u,iterationBudget:l,quadrature:c}=t,f=n.unknowns,p=s.map(y=>{if(typeof y=="function")return y.toString();throw new Error(`Unsupported import \`${y}\``)}).join(`
|
|
140
|
+
${r}`)}return this._entries[n]?.value}invalidate(n){delete this._entries[n]}purgeValues(){for(let n of Object.keys(this._entries)){let t=this._entries[n];t.value&&(t.purge?t.value=t.purge(t.value):delete this._entries[n])}}};var hr=class e extends Je{_kind="symbol";_hash;_id;_def;constructor(n,t,i){super(n,i?.metadata),yn(t),`${t}${vi(t)}`,this._id=t,this._def=i?.def}get json(){return Li(this._id)?this._id:{sym:this._id}}get hash(){return this._hash??=Fi(this._id),this._hash}_unshared(){return new e(this.engine,this._id,{metadata:{latex:this.verbatimLatex,sourceOffsets:this.sourceOffsets},def:this._def})}get isPure(){return!0}get isConstant(){let n=this._def;return(ie(n)&&n?.value.isConstant)??!1}bind(){}reset(){}get isCanonical(){return this._def!==void 0}set isCanonical(n){throw new Error("Setting the isCanonical property is not allowed. Use the canonical() method instead.")}get canonical(){return this._def?this:this.engine.symbol(this._id)}is(n,t){if(t===void 0&&this.isSame(n))return!0;let i=this.value;return i&&i!==this?i.is(n,t):!1}isSame(n){return n===!0?this.symbol==="True"||w(this.value,"True"):n===!1?this.symbol==="False"||w(this.value,"False"):n instanceof Je&&w(n)?this.symbol===n.symbol:this.value?.isSame(n)??!1}toNumericValue(){this.isCanonical||this.isStructural;let n=this.engine;return this.symbol==="ImaginaryUnit"?[n._numericValue({re:0,im:1}),n.One]:this.symbol==="PositiveInfinity"||this.isInfinity&&this.isPositive?[n._numericValue(1/0),n.One]:this.symbol==="NegativeInfinity"||this.isInfinity&&this.isNegative?[n._numericValue(-1/0),n.One]:this.symbol==="NaN"?[n._numericValue(NaN),n.One]:[n._numericValue(1),this]}neg(){return $a(this)}inv(){return this.engine._fn("Divide",[this.engine.One,this])}abs(){return this.isNonNegative?this:this.isNonPositive?this.neg():this.engine._fn("Abs",[this])}add(n){return n===0?this:te(this,this.engine.expr(n))}mul(n){if(n===1)return this;if(n===-1)return this.neg();if(n===0||n instanceof je&&n.isZero)return this.isNaN||this.isInfinity===!0?this.engine.NaN:this.engine.Zero;if(n instanceof je){if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return he(this,this.engine.expr(n))}div(n){return ll(this,n)}pow(n){return sn(this,n,{numericApproximation:!1})}root(n){let t=typeof n=="number"?n:n.im===0?n.re:void 0,i=this.engine;return this.symbol==="ComplexInfinity"||t===0?i.NaN:t===1?this:t===2?this.sqrt():t===-1?this.inv():t!==void 0&&t<0&&Number.isInteger(t)?i._fn("Divide",[i.One,this.root(-t)]):i._fn("Root",[this,i.expr(n)])}sqrt(){let n=this.engine;return this.symbol==="ComplexInfinity"?n.NaN:n._fn("Sqrt",[this])}ln(n){let t=n?this.engine.expr(n):void 0;return this.symbol==="ExponentialE"?!t||w(t,"ExponentialE")?this.engine.One:this.engine.One.div(t.ln()):t?t.re===10?this.engine._fn("Log",[this]):this.engine._fn("Log",[this,t]):this.engine._fn("Ln",[this])}solve(n){let t=La(n);return t.length!==1?null:t.includes(this.symbol)?[this.engine.Zero]:null}get complexity(){return 7}get operator(){return"Symbol"}get symbol(){return this._id}get baseDefinition(){return this.valueDefinition??this.operatorDefinition}get valueDefinition(){if(ie(this._def))return this._def.value}get operatorDefinition(){if(fe(this._def))return this._def.operator}infer(n,t="narrow"){if(!this._def)return!1;let i=this._def;if(ie(i)){if(i.value.isConstant)return!1;if(i.value.inferredType||i.value.type.isUnknown){let r=i.value.type.isUnknown,o=this.engine.type(t==="widen"?Te(i.value.type.type,n):fs(i.value.type.type,n));return o.isUnknown?!1:(i.value.type=o,r&&this.engine._inferenceTxDepth>0&&(this.engine._freshlyInferred??=new Set).add(i.value),!0)}return!1}if(fe(i)){let r=this.engine.type(t==="widen"?Te(i.operator.signature.type,n):fs(i.operator.signature.type,n));return r.matches("never")?!1:r.matches("function")?(i.operator.signature=r,this.engine._mutationGeneration+=1,!0):(Si(this.engine,this._id,i,{type:r.type}),!0)}return!1}get _value(){if(!this._def||fe(this._def))return;if(this._def.value.isConstant)return this._def.value.value;if(this._def.value.isSelfReferential)return;let n=this.engine._getSymbolValue(this._id);if(!(n!==void 0&&"symbol"in n&&n.symbol===this._id))return n}get value(){return fe(this._def)?this.engine._fn("Operator",[this.engine.string(this._id)]):this._value}set value(n){if(!this._def)throw new Error(`Cannot set value of non-canonical ${this._id}`);let t=this.engine;t.forget(this._id);let i;if(typeof n=="boolean"&&(n=n?t.True:t.False),typeof n=="string"&&(n=t.string(n)),typeof n=="object")if("re"in n&&"im"in n)n=t.number(t.complex(n.re??0,n.im));else if("num"in n&&"denom"in n)n=t.number([n.num,n.denom]);else if(Array.isArray(n))n=t._fn("List",n.map(r=>t.expr(r)));else throw new Error(`Invalid value for symbol ${this._id}: ${n}`);if(n!==void 0&&(i=t.expr(n).evaluate()),i?.type.matches("function")){delete this._def.value,this._def.operator={signature:i.type,evaluate:i};return}if(ie(this._def)&&this._def.value.isConstant)throw new Error(`The value of the constant "${this._id}" cannot be changed`);t._setSymbolValue(this._id,i)}get type(){let n=this._def;return ie(n)?n.value.type:fe(n)?n.operator.signature:Z.unknown}set type(n){if(!this._def)throw new Error(`Cannot set type of non-canonical symbol "${this._id}"`);if(this._id[0]==="_")throw new Error(`The type of the wildcard "${this._id}" cannot be changed`);this.engine.forget(this._id),typeof n=="string"?n=Y(n):n instanceof Z&&(n=n.type),n==="function"||jd(n)?fe(this._def)?this._def.operator.signature=n:Si(this.engine,this._id,this._def,{signature:n}):fe(this._def)?Si(this.engine,this._id,this._def,{type:n}):this._def.value.type=this.engine.type(n)}has(n){return typeof n=="string"?this._id===n:n.includes(this._id)}match(n,t){return Bl(this,n,t)}get shape(){let n=this.type.type;return typeof n=="object"&&n.kind==="list"&&n.dimensions?n.dimensions:[]}get rank(){return this.shape.length}get sgn(){return this.value?this.value.sgn:T6(this.engine,this.symbol)}get isOdd(){return this.value?.isOdd}get isEven(){return this.value?.isEven}get isFinite(){let n=this.value?.isFinite;if(n!==void 0)return n;let t=this.type;if(!t.isUnknown&&t.matches("finite_number"))return!0}get isInfinity(){return this.value?.isInfinity}get isNaN(){return this.value?.isNaN}get isPositive(){return $l(this.sgn)}get isNonPositive(){return Jl(this.sgn)}get isNegative(){return Vl(this.sgn)}get isNonNegative(){return ql(this.sgn)}get isNumber(){let n=this.type;if(!n.isUnknown)return n.matches("number")}get isInteger(){let n=this.type;if(!n.isUnknown){if(n.matches("integer"))return!0;if(!n.matches("real")){if(n.matches("number"))return gi(n.type)?!1:void 0;if(Bn({kind:"intersection",types:[n.type,"integer"]})==="nothing")return!1}}}get isRational(){let n=this.type;if(!n.isUnknown){if(n.matches("rational"))return!0;if(!n.matches("real")){if(n.matches("number"))return gi(n.type)?!1:void 0;if(Bn({kind:"intersection",types:[n.type,"rational"]})==="nothing")return!1}}}get isReal(){let n=this.type;if(!n.isUnknown){if(n.matches("real"))return!0;if(Xi(this.engine)&&_r(this.engine).membership.get(this._id)?.notIn.some(i=>w(i,"RealNumbers")))return!1;if(!(n.matches("number")&&!gi(n.type)))return!1}}get re(){return this.value?.re??NaN}get im(){return this.value?.im??NaN}get bignumRe(){return this.value?.bignumRe}get bignumIm(){return this.value?.bignumIm}simplify(n){return Qr(this,n).at(-1)?.value??this}explain(n,t){return Fl(this,n,t)}evaluate(n){let t=this.valueDefinition;if(!t)return this;let i=t.holdUntil;if(t.isConstant){if(n?.numericApproximation){if(i==="never"||i==="evaluate"||i==="N")return t.value?.N()??this}else if(i==="never"||i==="evaluate")return t.value?.evaluate(n)??this}else if(i==="never"||i==="evaluate"||i==="N"&&n?.numericApproximation){let r=this.engine._getSymbolValue(this._id)??this;return r.operator==="Unevaluated"&&(r=r.evaluate(n)??this),r}return this}N(){let n=this.valueDefinition;if(n&&!n.isConstant){let t=this._value;return t?N(t)?t.N():t.symbols.includes(this._id)?t:t.N():this}return n?.value?.N()??this}replace(n,t){return es(this,n,t).at(-1)?.value??null}subs(n,t){let i=t?.canonical??this.isCanonical;if(n[this._id]===void 0)return i?this.canonical:this;let r=i===!0?"canonical":i===!1?"raw":i;return this.engine.expr(n[this._id],{form:r})}get _asCollection(){if(ie(this._def))return this._def.value.collection}get isCollection(){return this._asCollection?.iterator!==void 0||(this._value?.isCollection??!1)}get isIndexedCollection(){return this._asCollection?.at!==void 0||(this._value?.isIndexedCollection??!1)}get isLazyCollection(){return this._asCollection?.isLazy?.(this._value??this)??this._value?.isLazyCollection??!1}contains(n){return this._asCollection?.contains?.(this._value??this,n)??this._value?.contains?.(n)}get count(){return this._asCollection?.count(this._value??this)??this._value?.count}get isEmptyCollection(){return this._asCollection?.isEmpty?.(this._value??this)??this._value?.isEmptyCollection}get isFiniteCollection(){return this._asCollection?.isFinite?.(this._value??this)??this._value?.isFiniteCollection}each(){let n=this._asCollection?.iterator?.(this._value??this);if(n){let t=this.engine;return(function*(){let i=n.next(),r=0;for(;!i.done;)(++r&255)===0&&z(t._deadline),yield i.value,i=n.next()})()}return this._value?.each()??(function*(){})()}at(n){let t=this._asCollection?.at;if(t){let i=this._value??this;if(n<0){if(this.isFiniteCollection!==!0)return this._value?.at?.(n);let o=this.count;if(o!==void 0&&Number.isFinite(o)){let s=o+1+n;if(s>=1){let a=t(i,s);if(a!==void 0)return a}return this._value?.at?.(n)}return this._value?.at?.(n)}let r=t(i,n);if(r!==void 0)return r}return this._value?.at?.(n)}get(n){return this._value?.get?.(n)}indexWhere(n){return this._asCollection?.indexWhere?this._asCollection.indexWhere(this._value??this,n):this._value?.indexWhere(n)}subsetOf(n,t){return this._asCollection?.subsetOf?.(this._value??this,n,t)??this._value?.subsetOf?.(n,t)??!1}};function CY(e,n){return e.lookupDefinition(n)}function G6(e,n){for(let t of Object.keys(n))n[t]=new hr(e,t,{def:CY(e,t)})}function U6(e){for(let n of Object.values(e))n?.reset()}function Jn(e){if(!Number.isFinite(e))throw new Error(`Cannot compile the non-finite value \`${e}\` to a GPU shader: GLSL/WGSL have no infinity or NaN literals.`);let n=e.toString();return!n.includes(".")&&!n.includes("e")&&!n.includes("E")?`${n}.0`:n}function Qe(e){if(!N(e)||e.im!==0)return;let n=e.re;if(isFinite(n))return n}var kY=/^-?\d+(\.\d+)?$/;function ra(e,n,t){let i=t==="+"?0:1,r=null,o=[];for(let s of e)if(kY.test(s)){let a=parseFloat(s);if(t==="*"&&a===0)return"0.0";r===null?r=a:r=t==="+"?r+a:r*a}else o.push(s);return r!==null&&r!==i&&o.unshift(Jn(r)),o.length===0?r!==null?Jn(r):n:o.length===1?o[0]:o.join(t==="+"?" + ":" * ")}function qb(e,n){return m(e,"Add")||m(e,"Subtract")?`(${n})`:n}function Z6(e,n){if(w(e,"ImaginaryUnit"))return{re:null,im:"1.0"};if(N(e)&&e.im!==0){let t=e.re,i=e.im;return{re:t!==0?Jn(t):null,im:Jn(i)}}if(m(e,"Multiply")){let t=e.ops,i=t.findIndex(r=>w(r,"ImaginaryUnit")||N(r)&&r.re===0&&r.im!==0);if(i>=0){let r=t[i],o=w(r,"ImaginaryUnit")?1:r.im,s=t.filter((l,c)=>c!==i);if(s.length===0)return{re:null,im:Jn(o)};let a=s.map(l=>qb(l,n(l)));return o!==1&&a.unshift(Jn(o)),{re:null,im:ra(a,"1.0","*")}}}return D.isComplexValued(e)?null:{re:n(e),im:null}}var SS={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],Divide:["/",13],LessEqual:["<=",9],GreaterEqual:[">=",9],Less:["<",9],Greater:[">",9],And:["&&",4],Or:["||",3],Not:["!",14]};function H6(e,n,t){if(n.length<2)throw new Error(`${e}: expected at least two arguments`);let i=n[0]?.engine?.tolerance??1e-10,r=l=>l.type.matches("collection")||tO(l);if(n.some(r)){if(n.length===2)return`_SYS.${e==="Equal"?"eq":"neq"}((${t(n[0])}), (${t(n[1])}), ${i})`;throw new Error(`${e}: cannot compile \u2014 chained (n-ary) comparison over an operand that may be a collection at run time (collection-valued or possibly-collection-typed). Materialize the collection first. Fail closed (D6).`)}let o=e==="Equal"?"<=":">",s=(l,c)=>{if(!(D.isComplexValued(l)||D.isComplexValued(c)))return`Math.abs((${t(l)}) - (${t(c)}))`;let p=h=>{let b=t(h);return D.isComplexValued(h)?{re:`(${b}).re`,im:`(${b}).im`}:{re:`(${b})`,im:"0"}},d=p(l),g=p(c);return`_SYS.cabs({ re: ${d.re} - ${g.re}, im: ${d.im} - ${g.im} })`},a=(l,c)=>`(${s(l,c)} ${o} ${i})`;if(n.length===2)return a(n[0],n[1]);let u=[];for(let l=0;l<n.length-1;l++)u.push(a(n[l],n[l+1]));return`(${u.join(" && ")})`}function go(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}function tO(e){let n=e.type.type;return n==="unknown"||n==="any"||n==="value"?m(e)&&(e.isCanonical||e.isStructural):typeof n!="string"&&n.kind==="broadcastable"}function _S(e,n,t){let i=t(e),r=e.type.type;return typeof r!="string"&&r.kind==="tuple"?`${i}[${n}]`:AY(e)?`(${i}).map((_pt) => _pt[${n}])`:`${i}[${n}]`}function AY(e){let n=De(e.type.type);if(n!==void 0&&typeof n!="string"&&n.kind==="tuple")return!0;if(e.isFiniteCollection){let t=e.at(1);if(t===void 0)return!1;let i=t.type.type;return typeof i!="string"&&i.kind==="tuple"||t.operator==="Tuple"}return!1}var NS={Equal:(e,n)=>H6("Equal",e,n),NotEqual:(e,n)=>H6("NotEqual",e,n),Abs:(e,n)=>D.isComplexValued(e[0])?`_SYS.cabs(${n(e[0])})`:D.isNonNegative(e[0])?n(e[0]):`Math.abs(${n(e[0])})`,Add:(e,n)=>{if(e.length===1)return n(e[0]);if(!e.some(u=>D.isComplexValued(u))){let u=e.map(Qe);if(u.every(c=>c!==void 0))return String(u.reduce((c,f)=>c+f,0));let l=e.filter(c=>Qe(c)!==0);return l.length===0?"0":l.length===1?n(l[0]):`(${l.map(c=>n(c)).join(" + ")})`}let i=[],r=e.map(u=>{let l=n(u),c=D.isComplexValued(u);if(c&&!w(u)&&!N(u)){let f=D.tempVar();return i.push([f,l]),{code:f,isComplex:c,bound:!0}}return{code:l,isComplex:c,bound:!1}}),o=r.map(u=>u.isComplex?u.bound?`${u.code}.re`:`(${u.code}).re`:u.code),s=r.filter(u=>u.isComplex).map(u=>u.bound?`${u.code}.im`:`(${u.code}).im`),a=`({ re: ${o.join(" + ")}, im: ${s.join(" + ")} })`;return i.length===0?a:`(() => { const ${i.map(([u,l])=>`${u} = ${l}`).join(", ")}; return ${a}; })()`},Arccos:(e,n)=>D.isComplexValued(e[0])?`_SYS.cacos(${n(e[0])})`:`Math.acos(${n(e[0])})`,Arcosh:"Math.acosh",Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return D.isComplexValued(e)?`_SYS.cacot(${n(e)})`:`(Math.PI / 2 - Math.atan(${n(e)}))`},Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return D.isComplexValued(e)?`_SYS.cacoth(${n(e)})`:`Math.atanh(1 / (${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return D.isComplexValued(e)?`_SYS.cacsc(${n(e)})`:`Math.asin(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return D.isComplexValued(e)?`_SYS.cacsch(${n(e)})`:`Math.asinh(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return D.isComplexValued(e)?`_SYS.casec(${n(e)})`:`Math.acos(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return D.isComplexValued(e)?`_SYS.casech(${n(e)})`:`Math.acosh(1 / (${n(e)}))`},Arcsin:(e,n)=>D.isComplexValued(e[0])?`_SYS.casin(${n(e[0])})`:`Math.asin(${n(e[0])})`,Arsinh:"Math.asinh",Arctan:(e,n)=>D.isComplexValued(e[0])?`_SYS.catan(${n(e[0])})`:`Math.atan(${n(e[0])})`,Artanh:"Math.atanh",Ceil:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.ceil(${n(e[0])})`,Chop:"_SYS.chop",Cos:(e,n)=>D.isComplexValued(e[0])?`_SYS.ccos(${n(e[0])})`:`Math.cos(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`_SYS.ccosh(${n(e[0])})`:`Math.cosh(${n(e[0])})`,Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");return D.isComplexValued(e)?`_SYS.ccot(${n(e)})`:D.inlineExpression("Math.cos(${x}) / Math.sin(${x})",n(e))},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return D.isComplexValued(e)?`_SYS.ccoth(${n(e)})`:D.inlineExpression("(Math.cosh(${x}) / Math.sinh(${x}))",n(e))},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return D.isComplexValued(e)?`_SYS.ccsc(${n(e)})`:`1 / Math.sin(${n(e)})`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return D.isComplexValued(e)?`_SYS.ccsch(${n(e)})`:`1 / Math.sinh(${n(e)})`},Exp:(e,n)=>D.isComplexValued(e[0])?`_SYS.cexp(${n(e[0])})`:`Math.exp(${n(e[0])})`,First:(e,n)=>`${n(e[0])}[0]`,Floor:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.floor(${n(e[0])})`,Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return D.inlineExpression("${x} - Math.floor(${x})",n(e))},Gamma:"_SYS.gamma",GCD:(e,n)=>eO("GCD",e,n),Integrate:(e,n,t)=>VY(e,n,t),LCM:(e,n)=>eO("LCM",e,n),Product:(e,n,t)=>W6("Product",e,n,t),Sum:(e,n,t)=>W6("Sum",e,n,t),Limit:(e,n)=>`_SYS.limit(${n(e[0])}, ${n(e[1])})`,Ln:(e,n)=>D.isComplexValued(e[0])?`_SYS.cln(${n(e[0])})`:`Math.log(${n(e[0])})`,List:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Matrix:(e,n)=>n(e[0]),Tuple:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Length:(e,n)=>{let t=e[0];if(t==null)throw new Error("Length: no argument");if(!go(t))throw new Error("Length: cannot compile \u2014 operand is not an indexed collection (list/vector/range). Fail closed (D6).");return`(${n(t)}).length`},At:(e,n)=>{let t=e[0],i=e[1];if(t==null||i===null||i===void 0)throw new Error("At: missing argument");if(e.length!==2)throw new Error("At: only the single-index form compiles; multi-index (nested) access is not supported. Fail closed (D6).");if(!go(t))throw new Error("At: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");return`_SYS.at(${n(t)}, ${n(i)})`},Reduce:(e,n,t)=>{let i=e[0],r=e[1],o=e[2];if(i==null||r===null||r===void 0)throw new Error("Reduce: missing argument");if(!go(i))throw new Error("Reduce: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=Q6(r);if(s===void 0&&(m(r,"Function")||w(r))){if(o==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");s=K6(r,n,t)}if(s===void 0)throw new Error("Reduce: the combiner does not compile to a function \u2014 only Add/Multiply/Min/Max folds, function literals, and user-defined functions compile on the JavaScript target. Fail closed (D6).");let a=n(i);return o!=null?`(${a}).reduce(${s}, ${n(o)})`:`((_l) => _l.length === 0 ? NaN : _l.reduce(${s}))(${a})`},Last:(e,n)=>`_SYS.at(${ve("Last",e[0],n)}, -1)`,Rest:(e,n)=>`(${ve("Rest",e[0],n)}).slice(1)`,Take:(e,n)=>{let t=ve("Take",e[0],n);if(e[1]==null)throw new Error("Take: missing count");return`(${t}).slice(0, Math.max(0, ${n(e[1])}))`},Drop:(e,n)=>{let t=ve("Drop",e[0],n);if(e[1]==null)throw new Error("Drop: missing count");return`(${t}).slice(Math.max(0, ${n(e[1])}))`},Reverse:(e,n)=>`(${ve("Reverse",e[0],n)}).slice().reverse()`,Sort:(e,n)=>{let t=ve("Sort",e[0],n);if(e.length>1)throw new Error("Sort: a custom comparator does not compile; only the default ascending numeric sort is supported. Fail closed (D6).");return`(${t}).slice().sort((_a, _b) => _a - _b)`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`...(${ve("Join",t,n,i+1)})`).join(", ")}]`,IndexOf:(e,n)=>{let t=ve("IndexOf",e[0],n);if(e[1]==null)throw new Error("IndexOf: missing value");let i=e[0]?.engine?.tolerance??1e-10;return`((_v) => (${t}).findIndex((_x) => Math.abs(_x - _v) <= ${i}) + 1)(${n(e[1])})`},Map:(e,n)=>{if(e.length>2)throw new Error("Map: multi-collection form is not compiled");let t=ve("Map",e[0],n);if(e[1]==null)throw new Error("Map: missing mapping function");return`((_f) => (${t}).map((_x) => _f(_x)))(${n(e[1])})`},Filter:(e,n)=>{let t=ve("Filter",e[0],n);if(e[1]==null)throw new Error("Filter: missing predicate");return`((_f) => (${t}).filter((_x) => _f(_x)))(${n(e[1])})`},CountIf:(e,n)=>{let t=ve("CountIf",e[0],n);if(e[1]==null)throw new Error("CountIf: missing predicate");return`((_f) => (${t}).filter((_x) => _f(_x)).length)(${n(e[1])})`},Find:(e,n)=>{let t=ve("Find",e[0],n);if(e[1]==null)throw new Error("Find: missing predicate");return`((_f) => ((${t}).find((_x) => _f(_x)) ?? NaN))(${n(e[1])})`},IndexWhere:(e,n)=>{let t=ve("IndexWhere",e[0],n);if(e[1]==null)throw new Error("IndexWhere: missing predicate");return`((_f) => (${t}).findIndex((_x) => _f(_x)) + 1)(${n(e[1])})`},Position:(e,n)=>{let t=ve("Position",e[0],n);if(e[1]==null)throw new Error("Position: missing predicate");return`((_f) => (${t}).flatMap((_x, _i) => _f(_x) ? [_i + 1] : []))(${n(e[1])})`},Tabulate:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Tabulate: missing argument");if(e.length>3)throw new Error("Tabulate: only the 1-D and 2-D forms compile. Fail closed (D6).");for(let o=1;o<e.length;o++){let s=Qe(e[o]);if(s!==void 0&&Math.round(s)<=0)throw new Error(`Tabulate: a statically non-positive dimension (${s}) is inert in the interpreter. Fail closed (D6).`)}let t=n(e[0]),i=n(e[1]);if(e.length===2)return`((_f, _n) => Array.from({ length: Math.max(0, Math.round(_n)) }, (_, _i) => _f(_i + 1)))(${t}, ${i})`;let r=n(e[2]);return`((_f, _n, _m) => Array.from({ length: Math.max(0, Math.round(_n)) }, (_, _i) => Array.from({ length: Math.max(0, Math.round(_m)) }, (_, _j) => _f(_i + 1, _j + 1))))(${t}, ${i}, ${r})`},Fill:(e,n)=>{let t=e[1];if(e[0]==null||t==null)throw new Error("Fill: missing argument");if(!m(t)||t.ops.length!==2)throw new Error("Fill: only the (function, (rows, cols)) form compiles. Fail closed (D6).");let i=n(e[0]),r=n(t.ops[0]),o=n(t.ops[1]);return`((_f, _r, _c) => Array.from({ length: Math.max(0, Math.round(_r)) }, (_, _i) => Array.from({ length: Math.max(0, Math.round(_c)) }, (_, _j) => _f(_i + 1, _j + 1))))(${i}, ${r}, ${o})`},Append:(e,n)=>{let t=ve("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[...(${t}), ${n(e[1])}]`},Most:(e,n)=>`(${ve("Most",e[0],n)}).slice(0, -1)`,Slice:(e,n)=>{let t=ve("Slice",e[0],n);if(e[1]==null||e[2]==null)throw new Error("Slice: missing index");return`((_l, _s, _e) => { _s = Math.round(_s); if (!Number.isFinite(_s)) _s = 1; _e = Math.round(_e); if (!Number.isFinite(_e)) _e = _l.length; if (_s < 1) _s = _l.length + 1 + _s; if (_s < 1) _s = 1; if (_s > _l.length) return []; if (_e < 1) _e = _l.length + 1 + _e; if (_e < 1) _e = 1; if (_e > _l.length) _e = _l.length; return _l.slice(_s - 1, _e); })(${t}, ${n(e[1])}, ${n(e[2])})`},IsEmpty:(e,n)=>`((${ve("IsEmpty",e[0],n)}).length === 0)`,Count:(e,n)=>`(${ve("Count",e[0],n)}).length`,Contains:(e,n)=>{e[0]&&du("Contains",e[0]);let t=ve("Contains",e[0],n);if(e[1]==null)throw new Error("Contains: missing value");return`(${t}).includes(${n(e[1])})`},Unique:(e,n)=>(e[0]&&du("Unique",e[0]),`[...new Set(${ve("Unique",e[0],n)})]`),RotateLeft:(e,n)=>{let t=ve("RotateLeft",e[0],n),i=e[1]==null?"1":n(e[1]);return`((_l, _n) => { if (_l.length === 0) return []; _n = Math.round(_n); if (!Number.isFinite(_n)) _n = 1; _n = ((_n % _l.length) + _l.length) % _l.length; return [..._l.slice(_n), ..._l.slice(0, _n)]; })(${t}, ${i})`},RotateRight:(e,n)=>{let t=ve("RotateRight",e[0],n),i=e[1]==null?"1":n(e[1]);return`((_l, _n) => { if (_l.length === 0) return []; _n = Math.round(_n); if (!Number.isFinite(_n)) _n = 1; _n = ((-_n % _l.length) + _l.length) % _l.length; return [..._l.slice(_n), ..._l.slice(0, _n)]; })(${t}, ${i})`},Zip:(e,n)=>e.length===0?"[]":`((..._ls) => Array.from({ length: Math.min(..._ls.map((_l) => _l.length)) }, (_, _i) => _ls.map((_l) => _l[_i])))(${e.map((i,r)=>ve("Zip",i,n,r+1)).join(", ")})`,Linspace:(e,n)=>{if(e[0]==null)throw new Error("Linspace: missing argument");let t=e[1]==null?"1":n(e[0]),i=e[1]==null?n(e[0]):n(e[1]),r=e[2]==null?"50":n(e[2]);return`((_s, _e, _c) => { _c = Math.floor(_c); if (!Number.isFinite(_c)) _c = 50; _c = Math.max(0, _c); if (_c === 1) return [_s]; return Array.from({ length: _c }, (_, _i) => _s + ((_e - _s) * _i) / (_c - 1)); })(${t}, ${i}, ${r})`},Chunk:(e,n)=>{let t=ve("Chunk",e[0],n);if(e[1]==null)throw new Error("Chunk: missing count");let i=Qe(e[1]);if(i!==void 0&&!(Math.round(i)>0))throw new Error(`Chunk: a statically non-positive chunk count (${i}) is inert in the interpreter. Fail closed (D6).`);return`((_l, _k) => { _k = Math.round(_k); if (!(Number.isFinite(_k) && _k > 0)) return []; const _sz = Math.ceil(_l.length / _k); return Array.from({ length: _k }, (_, _i) => _l.slice(_i * _sz, (_i + 1) * _sz)); })(${t}, ${n(e[1])})`},Partition:(e,n)=>{let t=ve("Partition",e[0],n),i=e[1];if(i==null)throw new Error("Partition: missing operand");if(i.type.matches("number")){let r=Qe(i);if(r!==void 0&&!(Math.round(r)>0))throw new Error(`Partition: a statically non-positive chunk size (${r}) is inert in the interpreter. Fail closed (D6).`);let o=e[2];if(o!==void 0){let s=Qe(o);if(s!==void 0&&!(Math.round(s)>0))throw new Error(`Partition: a statically non-positive step (${s}) is inert in the interpreter. Fail closed (D6).`);return`((_l, _n, _s) => { _n = Math.round(_n); _s = Math.round(_s); if (!(Number.isFinite(_n) && _n > 0 && Number.isFinite(_s) && _s > 0)) return []; const _r = []; for (let _i = 0; _i + _n <= _l.length; _i += _s) _r.push(_l.slice(_i, _i + _n)); return _r; })(${t}, ${n(i)}, ${n(o)})`}return`((_l, _n) => { _n = Math.round(_n); if (!(Number.isFinite(_n) && _n > 0)) return []; const _r = []; for (let _i = 0; _i < _l.length; _i += _n) _r.push(_l.slice(_i, _i + _n)); return _r; })(${t}, ${n(i)})`}if(m(i,"Function")||w(i)&&D.userFunctionLiteral(i.engine,i.symbol)!==void 0)return`((_f, _l) => { const _t = [], _u = []; for (const _x of _l) (_f(_x) ? _t : _u).push(_x); return [_t, _u]; })(${n(i)}, ${t})`;throw new Error("Partition: the second operand must be an integer or a function literal. Fail closed (D6).")},Ordering:(e,n)=>{let t=ve("Ordering",e[0],n);if(e.length>1)throw new Error("Ordering: a custom ordering function does not compile; only the default ascending numeric order is supported. Fail closed (D6).");return`((_l) => Array.from({ length: _l.length }, (_, _i) => _i + 1).sort((_a, _b) => _l[_a - 1] - _l[_b - 1]))(${t})`},Shuffle:(e,n,t)=>{let i=ve("Shuffle",e[0],n);if(e.length>1)throw new Error("Shuffle: the seeded form does not compile. Fail closed (D6).");let r=t?.randomSeed;if(r!=null){let o=t?.randomState?t.randomState.counter++:0,s=(r^Math.imul(o+1,2654435761))>>>0;return`_SYS.shuffle(${i}, ${s})`}return`_SYS.shuffle(${i})`},Any:(e,n)=>{let t=ve("Any",e[0],n);if(e[1]==null)throw new Error("Any: only the predicate form compiles. Fail closed (D6).");return`((_f) => (${t}).some((_x) => _f(_x)))(${n(e[1])})`},All:(e,n)=>{let t=ve("All",e[0],n);if(e[1]==null)throw new Error("All: only the predicate form compiles. Fail closed (D6).");return`((_f) => (${t}).every((_x) => _f(_x)))(${n(e[1])})`},TakeWhile:(e,n)=>{let t=ve("TakeWhile",e[0],n);if(e[1]==null)throw new Error("TakeWhile: missing predicate");return`((_f, _l) => { const _i = _l.findIndex((_x) => !_f(_x)); return _i < 0 ? _l.slice() : _l.slice(0, _i); })(${n(e[1])}, ${t})`},DropWhile:(e,n)=>{let t=ve("DropWhile",e[0],n);if(e[1]==null)throw new Error("DropWhile: missing predicate");return`((_f, _l) => { const _i = _l.findIndex((_x) => !_f(_x)); return _i < 0 ? [] : _l.slice(_i); })(${n(e[1])}, ${t})`},FlatMap:(e,n)=>{let t=ve("FlatMap",e[0],n);if(e[1]==null)throw new Error("FlatMap: missing mapping function");return`((_f) => (${t}).flatMap((_x) => _f(_x)))(${n(e[1])})`},Scan:(e,n,t)=>{let i=e[0],r=e[1],o=e[2];if(i==null||r==null)throw new Error("Scan: missing argument");if(!go(i))throw new Error("Scan: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=Q6(r)??(m(r,"Function")||w(r)?K6(r,n,t):void 0);if(s===void 0)throw new Error("Scan: the combiner does not compile to a function \u2014 only Add/Multiply/Min/Max folds, function literals, and user-defined functions compile on the JavaScript target. Fail closed (D6).");let a=n(i);return o!=null?`((_f, _l, _a) => _l.map((_x) => (_a = _f(_a, _x))))(${s}, ${a}, ${n(o)})`:`((_f, _l) => { let _a; return _l.map((_x, _i) => (_a = _i === 0 ? _x : _f(_a, _x))); })(${s}, ${a})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");let t=n(e[0]);return D.isBooleanValued(e[0])?`((${t}) ? 1 : 0)`:`(_SYS.cond(${t}) ? 1 : 0)`},KroneckerDelta:(e,n)=>{if(e.length===0||e[0]==null)throw new Error("KroneckerDelta: missing argument");let t=e[0].engine.tolerance??1e-10;return e.length===1?`(Math.abs(${n(e[0])}) <= ${t} ? 1 : 0)`:`((..._v) => _v.every((_x) => Math.abs(_x - _v[0]) <= ${t}) ? 1 : 0)(${e.map(i=>n(i)).join(", ")})`},Element:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Element: missing argument");return du("Element",e[1]),`(${ve("Element",e[1],n)}).includes(${n(e[0])})`},Identity:(e,n)=>{if(e[0]==null)throw new Error("Identity: missing argument");return n(e[0])},Apply:(e,n)=>{if(e[0]==null)throw new Error("Apply: missing function");return`(${n(e[0])})(${e.slice(1).map(t=>n(t)).join(", ")})`},Dot:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Dot: missing argument");return`_SYS.matmul(${ve("Dot",e[0],n,1)}, ${ve("Dot",e[1],n,2)})`},MatrixMultiply:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixMultiply: missing argument");return`_SYS.matmul(${ve("MatrixMultiply",e[0],n,1)}, ${ve("MatrixMultiply",e[1],n,2)})`},Cross:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Cross: missing argument");return`_SYS.cross(${ve("Cross",e[0],n,1)}, ${ve("Cross",e[1],n,2)})`},Norm:(e,n)=>{if(e[0]==null)throw new Error("Norm: missing argument");if(e[1]!=null){if(q(e[1])){if(e[1].string==="Frobenius")return`_SYS.norm(${n(e[0])})`;throw new Error(`Norm: the "${e[1].string}" norm does not compile. Fail closed (D6).`)}return`_SYS.norm(${n(e[0])}, ${n(e[1])})`}return`_SYS.norm(${n(e[0])})`},Transpose:(e,n)=>{if(e.length>1)throw new Error("Transpose: explicit axes do not compile. Fail closed (D6).");return`_SYS.transpose(${ve("Transpose",e[0],n)})`},Determinant:(e,n)=>`_SYS.det(${ve("Determinant",e[0],n)})`,Inverse:(e,n)=>`_SYS.inv(${ve("Inverse",e[0],n)})`,Trace:(e,n)=>{if(e.length>1)throw new Error("Trace: explicit axes do not compile. Fail closed (D6).");return`_SYS.trace(${ve("Trace",e[0],n)})`},ConjugateTranspose:(e,n)=>{if(e.length>1)throw new Error("ConjugateTranspose: explicit axes do not compile. Fail closed (D6).");return`_SYS.conjTranspose(${ve("ConjugateTranspose",e[0],n)})`},Diagonal:(e,n)=>{if(e.length>1)throw new Error("Diagonal: the offset/banded form does not compile. Fail closed (D6).");return`_SYS.diagonal(${ve("Diagonal",e[0],n)})`},MatrixPower:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixPower: missing argument");return`_SYS.matpow(${ve("MatrixPower",e[0],n)}, ${n(e[1])})`},RowReduce:(e,n)=>`_SYS.rref(${ve("RowReduce",e[0],n)})`,Rank:(e,n)=>{if(e[0]==null)throw new Error("Rank: missing argument");return`(_SYS.shape(${n(e[0])}).length)`},Shape:(e,n)=>{if(e[0]==null)throw new Error("Shape: missing argument");return`_SYS.shape(${n(e[0])})`},Flatten:(e,n)=>{let t=ve("Flatten",e[0],n);return e[1]!=null?`(${t}).flat(${n(e[1])})`:`(${t}).flat(Infinity)`},Reshape:(e,n)=>{let t=ve("Reshape",e[0],n),i=e[1];if(i==null)throw new Error("Reshape: missing shape");if(!m(i)||i.ops.length===0||i.ops.length>2)throw new Error("Reshape: only a 1-D or 2-D target shape compiles. Fail closed (D6).");return`_SYS.reshape(${t}, [${i.ops.map(r=>n(r)).join(", ")}])`},Log:(e,n)=>e.length===1?`Math.log10(${n(e[0])})`:`(Math.log(${n(e[0])}) / Math.log(${n(e[1])}))`,GammaLn:"_SYS.lngamma",Lb:"Math.log2",ElementMax:(e,n)=>`Math.max(${e.map(t=>n(t)).join(", ")})`,ElementMin:(e,n)=>`Math.min(${e.map(t=>n(t)).join(", ")})`,Clamp:(e,n)=>`Math.min(Math.max(${n(e[0])}, ${n(e[1])}), ${n(e[2])})`,Max:(e,n)=>X6("Max",e,n),Mean:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.mean(${n(e[0])})`:`_SYS.mean([${e.map(t=>n(t)).join(", ")}])`,Median:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.median(${n(e[0])})`:`_SYS.median([${e.map(t=>n(t)).join(", ")}])`,Variance:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.variance(${n(e[0])})`:`_SYS.variance([${e.map(t=>n(t)).join(", ")}])`,PopulationVariance:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.populationVariance(${n(e[0])})`:`_SYS.populationVariance([${e.map(t=>n(t)).join(", ")}])`,StandardDeviation:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.standardDeviation(${n(e[0])})`:`_SYS.standardDeviation([${e.map(t=>n(t)).join(", ")}])`,PopulationStandardDeviation:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.populationStandardDeviation(${n(e[0])})`:`_SYS.populationStandardDeviation([${e.map(t=>n(t)).join(", ")}])`,Kurtosis:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.kurtosis(${n(e[0])})`:`_SYS.kurtosis([${e.map(t=>n(t)).join(", ")}])`,Skewness:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.skewness(${n(e[0])})`:`_SYS.skewness([${e.map(t=>n(t)).join(", ")}])`,Mode:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.mode(${n(e[0])})`:`_SYS.mode([${e.map(t=>n(t)).join(", ")}])`,Quartiles:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.quartiles(${n(e[0])})`:`_SYS.quartiles([${e.map(t=>n(t)).join(", ")}])`,InterquartileRange:(e,n)=>e.length===0?"NaN":e.length===1?`_SYS.interquartileRange(${n(e[0])})`:`_SYS.interquartileRange([${e.map(t=>n(t)).join(", ")}])`,Covariance:(e,n)=>{if(e.length!==2)throw new Error("Covariance: expected two collection arguments to compile");return`_SYS.covariance(${n(e[0])}, ${n(e[1])})`},PopulationCovariance:(e,n)=>{if(e.length!==2)throw new Error("PopulationCovariance: expected two collection arguments to compile");return`_SYS.populationCovariance(${n(e[0])}, ${n(e[1])})`},Correlation:(e,n)=>{if(e.length!==2)throw new Error("Correlation: expected two collection arguments to compile");return`_SYS.correlation(${n(e[0])}, ${n(e[1])})`},Min:(e,n)=>X6("Min",e,n),Power:(e,n)=>{let t=e[0],i=e[1];if(t===null)throw new Error("Power: no argument");if(D.isComplexValued(t)||D.isComplexValued(i))return`_SYS.cpow(${n(t)}, ${n(i)})`;let r=Qe(t),o=Qe(i);if(r!==void 0&&o!==void 0){let s=Math.pow(r,o);if(Number.isNaN(s))throw new Error(`Power(${r}, ${o}) has no real value; cannot compile to a real target`);return String(s)}if(o===0)return"1";if(o===1)return n(t);if(o===2&&(w(t)||N(t))){let s=n(t);return`(${s} * ${s})`}return o===-1?`(1 / (${n(t)}))`:o===.5?`Math.sqrt(${n(t)})`:o===1/3?`Math.cbrt(${n(t)})`:o===-.5?`(1 / Math.sqrt(${n(t)}))`:o===void 0?`_SYS.pow(${n(t)}, ${n(i)})`:`Math.pow(${n(t)}, ${n(i)})`},Range:(e,n)=>{if(e.length===0)return"[]";if(e.length===1)return`Array.from({length: ${n(e[0])}}, (_, i) => i)`;let t=n(e[0]),i=n(e[1]),r=e[2]?n(e[2]):"1";if(t===null)throw new Error("Range: no start");if(i===null&&(i=t,t="1"),r==="0")throw new Error("Range: step cannot be zero");if(e[2]===void 0||e[2]===null){let o=parseFloat(i),s=parseFloat(t);if(!isNaN(o)&&!isNaN(s)){let a=o>=s?1:-1,u=Math.floor(Math.abs(o-s))+1;return u<50?`[${Array.from({length:u},(l,c)=>s+a*c).join(", ")}]`:`Array.from({length: ${u}}, (_e, i) => ${t} ${a===1?"+":"-"} i)`}return`((_a, _b) => Array.from({length: Math.floor(Math.abs(_b - _a)) + 1}, (_e, _i) => _b >= _a ? _a + _i : _a - _i))(${t}, ${i})`}return`Array.from({length: Math.floor((${i} - ${t}) / ${r}) + 1}, (_e, i) => ${t} + i * ${r})`},Root:([e,n],t)=>{if(e===null)throw new Error("Root: no argument");if(n===null)return`Math.sqrt(${t(e)})`;let i=Qe(e),r=Qe(n);if(i!==void 0&&r!==void 0&&r!==0){let o=Math.pow(i,1/r);if(Number.isNaN(o)){if(Number.isInteger(r)&&r%2!==0&&i<0)return String(-Math.pow(-i,1/r));throw new Error(`Root(${i}, ${r}) has no real value; cannot compile to a real target`)}return String(o)}return r===2?`Math.sqrt(${t(e)})`:r===3?`Math.cbrt(${t(e)})`:r!==void 0&&Number.isInteger(r)&&r%2!==0?D.inlineExpression(`(Math.sign(\${x}) * Math.pow(Math.abs(\${x}), ${1/r}))`,t(e)):r!==void 0?`Math.pow(${t(e)}, ${1/r})`:`Math.pow(${t(e)}, 1 / (${t(n)}))`},Random:(e,n,t)=>{let i=t?.randomSeed,r=e.length===1&&!D.isIntegerValued(e[0]);if(i!=null&&!r){let a=t?.randomState?t.randomState.counter++:0,u=dp((i^Math.imul(a+1,2654435761))>>>0)();if(e.length===0)return u.toString();if(e.length===2){let l=n(e[0]),c=n(e[1]);return`((${l}) + Math.floor(${u} * ((${c}) - (${l}))))`}return`Math.floor(${u} * (${n(e[0])}))`}if(e.length===0)return"Math.random()";if(e.length===2){let a=n(e[0]),u=n(e[1]);return`((${a}) + Math.floor(Math.random() * ((${u}) - (${a}))))`}let o=e[0];return D.isIntegerValued(o)?`Math.floor(Math.random() * (${n(o)}))`:`(() => { const _s = (${n(o)}) * 12.9898; const _v = Math.sin(_s) * 43758.5453; return _v - Math.floor(_v); })()`},Round:(e,n)=>{if(e.length<2)return D.isIntegerValued(e[0])?n(e[0]):D.inlineExpression("(Math.sign(${x}) * Math.round(Math.abs(${x})))",n(e[0]));let t=D.tempVar(),i=D.tempVar();return`(() => { const ${i} = Math.pow(10, ${n(e[1])}); const ${t} = ${n(e[0])} * ${i}; return (Math.sign(${t}) * Math.round(Math.abs(${t}))) / ${i}; })()`},Square:(e,n)=>{let t=e[0];if(t===null)throw new Error("Square: no argument");let i=Qe(t);if(i!==void 0)return String(i*i);if(w(t)){let r=n(t);return`(${r} * ${r})`}return`Math.pow(${n(t)}, 2)`},Sec:(e,n)=>{let t=e[0];if(t===null)throw new Error("Sec: no argument");return D.isComplexValued(t)?`_SYS.csec(${n(t)})`:`1 / Math.cos(${n(t)})`},Sech:(e,n)=>{let t=e[0];if(t===null)throw new Error("Sech: no argument");return D.isComplexValued(t)?`_SYS.csech(${n(t)})`:`1 / Math.cosh(${n(t)})`},Second:(e,n)=>`${n(e[0])}[1]`,Heaviside:"_SYS.heaviside",Sign:"Math.sign",Sinc:"_SYS.sinc",FresnelS:"_SYS.fresnelS",FresnelC:"_SYS.fresnelC",Sin:(e,n)=>D.isComplexValued(e[0])?`_SYS.csin(${n(e[0])})`:`Math.sin(${n(e[0])})`,Sinh:(e,n)=>D.isComplexValued(e[0])?`_SYS.csinh(${n(e[0])})`:`Math.sinh(${n(e[0])})`,Sqrt:(e,n)=>{if(D.isComplexValued(e[0]))return`_SYS.csqrt(${n(e[0])})`;let t=Qe(e[0]);if(t!==void 0){let i=Math.sqrt(t);if(Number.isNaN(i))throw new Error(`Sqrt(${t}) has no real value; cannot compile to a real target`);return String(i)}return`Math.sqrt(${n(e[0])})`},Tan:(e,n)=>D.isComplexValued(e[0])?`_SYS.ctan(${n(e[0])})`:`Math.tan(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`_SYS.ctanh(${n(e[0])})`:`Math.tanh(${n(e[0])})`,Third:(e,n)=>`${n(e[0])}[2]`,PointX:(e,n)=>_S(e[0],0,n),PointY:(e,n)=>_S(e[0],1,n),PointZ:(e,n)=>_S(e[0],2,n),Mod:([e,n],t)=>{if(e===null||n===null)throw new Error("Mod: missing argument");let i=t(e),r=t(n);return D.isIntegerValued(e)&&D.isIntegerValued(n)&&D.isNonNegative(e)?`(${i} % ${r})`:`(((${i} % ${r}) + ${r}) % ${r})`},Truncate:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`Math.trunc(${n(e[0])})`,Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");return`(${t(e)} - ${t(n)} * Math.round(${t(e)} / ${t(n)}))`},Divide:([e,n],t)=>{if(e===null||n===null)throw new Error("Divide: missing argument");let i=D.isComplexValued(e),r=D.isComplexValued(n);if(!i&&!r){let o=Qe(e),s=Qe(n);return o!==void 0&&s!==void 0&&s!==0?String(o/s):s===1?t(e):`(${t(e)} / ${t(n)})`}return i&&r?`(() => { const _a = ${t(e)}, _b = ${t(n)}, _d = _b.re * _b.re + _b.im * _b.im; return { re: (_a.re * _b.re + _a.im * _b.im) / _d, im: (_a.im * _b.re - _a.re * _b.im) / _d }; })()`:i&&!r?`(() => { const _a = ${t(e)}, _r = ${t(n)}; return { re: _a.re / _r, im: _a.im / _r }; })()`:`(() => { const _r = ${t(e)}, _b = ${t(n)}, _d = _b.re * _b.re + _b.im * _b.im; return { re: _r * _b.re / _d, im: -_r * _b.im / _d }; })()`},Negate:([e],n)=>{if(e===null)throw new Error("Negate: no argument");if(!D.isComplexValued(e)){let t=Qe(e);return t!==void 0?String(-t):`(-${n(e)})`}return`_SYS.cneg(${n(e)})`},Multiply:(e,n)=>{if(e.length===1)return n(e[0]);if(!e.some(s=>D.isComplexValued(s))){if(e.some(u=>Qe(u)===0))return"0";let s=e.map(Qe);if(s.every(u=>u!==void 0))return String(s.reduce((u,l)=>u*l,1));let a=e.filter(u=>Qe(u)!==1);return a.length===0?"1":a.length===1?n(a[0]):`(${a.map(u=>n(u)).join(" * ")})`}if(e.length===2){let s=D.isComplexValued(e[0]),a=D.isComplexValued(e[1]),u=n(e[0]),l=n(e[1]);return s&&a?`(() => { const _a = ${u}, _b = ${l}; return { re: _a.re * _b.re - _a.im * _b.im, im: _a.re * _b.im + _a.im * _b.re }; })()`:s&&!a?`(() => { const _a = ${u}, _r = ${l}; return { re: _a.re * _r, im: _a.im * _r }; })()`:`(() => { const _r = ${u}, _b = ${l}; return { re: _r * _b.re, im: _r * _b.im }; })()`}let i=[],r=[];for(let s=0;s<e.length;s++){let a=`_v${s}`;r.push(a),i.push(`const ${a} = ${n(e[s])}`)}let o=D.isComplexValued(e[0]);i.push(`let _re = ${o?`${r[0]}.re`:r[0]}`),i.push(`let _im = ${o?`${r[0]}.im`:"0"}`);for(let s=1;s<e.length;s++){let a=r[s],u=D.isComplexValued(e[s]),l=u?`${a}.re`:a,c=u?`${a}.im`:"0";i.push(`const _nre${s} = _re * ${l} - _im * ${c}`),i.push(`const _nim${s} = _re * ${c} + _im * ${l}`),i.push(`_re = _nre${s}`),i.push(`_im = _nim${s}`)}return`(() => { ${i.join("; ")}; return { re: _re, im: _im }; })()`},Factorial:"_SYS.factorial",Factorial2:"_SYS.factorial2",Exp2:([e],n)=>{if(e===null)throw new Error("Exp2: no argument");return`Math.pow(2, ${n(e)})`},Log2:"Math.log2",Log10:"Math.log10",Lg:"Math.log10",Arctan2:"Math.atan2",Hypot:"Math.hypot",Degrees:([e],n)=>{if(e===null)throw new Error("Degrees: no argument");return`(${n(e)} * Math.PI / 180)`},Haversine:([e],n)=>{if(e===null)throw new Error("Haversine: no argument");return D.inlineExpression("(1 - Math.cos(${x})) / 2",n(e))},InverseHaversine:([e],n)=>{if(e===null)throw new Error("InverseHaversine: no argument");return`(2 * Math.asin(Math.sqrt(${n(e)})))`},Erf:"_SYS.erf",Erfc:"_SYS.erfc",ErfInv:"_SYS.erfInv",Erfi:"_SYS.erfi",Beta:"_SYS.beta",GammaRegularized:"_SYS.gammaQ",BetaRegularized:"_SYS.betaRegularized",Digamma:"_SYS.digamma",Trigamma:"_SYS.trigamma",PolyGamma:(e,n)=>`_SYS.polygamma(${n(e[0])}, ${n(e[1])})`,Zeta:"_SYS.zeta",LambertW:"_SYS.lambertW",BesselJ:(e,n)=>`_SYS.besselJ(${n(e[0])}, ${n(e[1])})`,BesselY:(e,n)=>`_SYS.besselY(${n(e[0])}, ${n(e[1])})`,BesselI:(e,n)=>`_SYS.besselI(${n(e[0])}, ${n(e[1])})`,BesselK:(e,n)=>`_SYS.besselK(${n(e[0])}, ${n(e[1])})`,AiryAi:"_SYS.airyAi",AiryBi:"_SYS.airyBi",AiryAiPrime:"_SYS.airyAiPrime",AiryBiPrime:"_SYS.airyBiPrime",SinIntegral:"_SYS.sinIntegral",CosIntegral:"_SYS.cosIntegral",ExpIntegralEi:"_SYS.expIntegralEi",LogIntegral:"_SYS.logIntegral",AGM:(e,n)=>e.length===1?`_SYS.agm(1, ${n(e[0])})`:`_SYS.agm(${n(e[0])}, ${n(e[1])})`,EllipticK:"_SYS.ellipticK",EllipticE:(e,n)=>e.length===2?`_SYS.ellipticEIncomplete(${n(e[0])}, ${n(e[1])})`:`_SYS.ellipticE(${n(e[0])})`,EllipticF:(e,n)=>`_SYS.ellipticF(${n(e[0])}, ${n(e[1])})`,EllipticPi:(e,n)=>e.length===3?`_SYS.ellipticPiIncomplete(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.ellipticPiComplete(${n(e[0])}, ${n(e[1])})`,Hypergeometric2F1:(e,n)=>`_SYS.hypergeometric2F1(${n(e[0])}, ${n(e[1])}, ${n(e[2])}, ${n(e[3])})`,Hypergeometric1F1:(e,n)=>`_SYS.hypergeometric1F1(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`,Mandelbrot:([e,n],t)=>{if(e===null||n===null)throw new Error("Mandelbrot: missing arguments");return`_SYS.mandelbrot(${t(e)}, ${t(n)})`},Julia:([e,n,t],i)=>{if(e===null||n===null||t===null)throw new Error("Julia: missing arguments");return`_SYS.julia(${i(e)}, ${i(n)}, ${i(t)})`},Binomial:(e,n)=>`_SYS.binomial(${n(e[0])}, ${n(e[1])})`,Choose:(e,n)=>`_SYS.binomial(${n(e[0])}, ${n(e[1])})`,Fibonacci:"_SYS.fibonacci",Real:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).re`:n(e[0]),Imaginary:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).im`:"0",Argument:(e,n)=>D.isComplexValued(e[0])?`_SYS.carg(${n(e[0])})`:`(${n(e[0])} >= 0 ? 0 : Math.PI)`,Conjugate:(e,n)=>D.isComplexValued(e[0])?`_SYS.cconj(${n(e[0])})`:n(e[0]),Color:([e],n)=>{if(e===null)throw new Error("Color: no argument");return`_SYS.color(${n(e)})`},ColorToString:(e,n)=>{if(e.length===0)throw new Error("ColorToString: no argument");return e.length>=2?`_SYS.colorToString(${n(e[0])}, ${n(e[1])})`:`_SYS.colorToString(${n(e[0])})`},ColorMix:(e,n)=>{if(e.length<2)throw new Error("ColorMix: need two colors");return e.length>=3?`_SYS.colorMix(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.colorMix(${n(e[0])}, ${n(e[1])})`},ColorContrast:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorContrast: need two colors");return`_SYS.colorContrast(${t(e)}, ${t(n)})`},ContrastingColor:(e,n)=>{if(e.length===0)throw new Error("ContrastingColor: no argument");return e.length>=3?`_SYS.contrastingColor(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`_SYS.contrastingColor(${n(e[0])})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");return`_SYS.colorToColorspace(${t(e)}, ${t(n)})`},ColorFromColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorFromColorspace: need components and space");return`_SYS.colorFromColorspace(${t(e)}, ${t(n)})`},Colormap:(e,n)=>{if(e.length===0)throw new Error("Colormap: no argument");return e.length>=2?`_SYS.colormap(${n(e[0])}, ${n(e[1])})`:`_SYS.colormap(${n(e[0])})`},Rgb:(e,n)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_SYS.rgb(${e.map(n).join(", ")})`},Hsv:(e,n)=>{if(e.length<3)throw new Error("Hsv: need 3 components");return`_SYS.hsv(${e.map(n).join(", ")})`},Hsl:(e,n)=>{if(e.length<3)throw new Error("Hsl: need 3 components");return`_SYS.hsl(${e.map(n).join(", ")})`},Oklab:(e,n)=>{if(e.length<3)throw new Error("Oklab: need 3 components");return`_SYS.oklab(${e.map(n).join(", ")})`},Oklch:(e,n)=>{if(e.length<3)throw new Error("Oklch: need 3 components");return`_SYS.oklch(${e.map(n).join(", ")})`},AsRgb:([e],n)=>{if(e===null)throw new Error("AsRgb: no argument");return`_SYS.asRgb(${n(e)})`},AsHsv:([e],n)=>{if(e===null)throw new Error("AsHsv: no argument");return`_SYS.asHsv(${n(e)})`},AsHsl:([e],n)=>{if(e===null)throw new Error("AsHsl: no argument");return`_SYS.asHsl(${n(e)})`},AsOklab:([e],n)=>{if(e===null)throw new Error("AsOklab: no argument");return`_SYS.asOklab(${n(e)})`},AsOklch:([e],n)=>{if(e===null)throw new Error("AsOklch: no argument");return n(e)},ColorDelta:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorDelta: need two colors");return`_SYS.colorDelta(${t(e)}, ${t(n)})`},Distance:([e,n],t)=>{if(e===null||n===null)throw new Error("Distance: need two points");return`_SYS.distance(${t(e)}, ${t(n)})`}};function dn(e){return{re:e.re,im:e.im}}function br(e){if(e!==void 0&&Number.isFinite(e)&&!(Math.abs(e-1)<1e-9))return e}function mo(e){if(typeof e=="string"){let t=Pt(e),i={r:t>>>24&255,g:t>>>16&255,b:t>>>8&255},r=br((t&255)/255);return r!==void 0&&(i.alpha=r),i}let n=Hs({L:e[0],C:e[1],H:e[2]});if(e.length>=4){let t=br(e[3]);t!==void 0&&(n.alpha=t)}return n}function hd(e){if(typeof e=="string"){let n=Pt(e),t=n>>>24&255,i=n>>>16&255,r=n>>>8&255,o=Pn({r:t,g:i,b:r}),s=br((n&255)/255);return s!==void 0&&(o.alpha=s),o}return{L:e[0],C:e[1],H:e[2],alpha:e.length>=4?br(e[3]):void 0}}function Vb(e){let n=e>>>24&255,t=e>>>16&255,i=e>>>8&255,r=Pn({r:n,g:t,b:i}),o=br((e&255)/255);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]}var RY={color(e){return Vb(Pt(e))},colorToString(e,n){let t=mo(e),i=(n??"hex").toLowerCase();switch(i){case"hex":{let r=Math.round(Math.max(0,Math.min(255,t.r))),o=Math.round(Math.max(0,Math.min(255,t.g))),s=Math.round(Math.max(0,Math.min(255,t.b))),a=`#${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;if(t.alpha!==void 0){let u=Math.round(Math.max(0,Math.min(255,t.alpha*255)));a+=u.toString(16).padStart(2,"0")}return a}case"rgb":{let r=Math.round(t.r),o=Math.round(t.g),s=Math.round(t.b);return t.alpha!==void 0?`rgb(${r} ${o} ${s} / ${t.alpha})`:`rgb(${r} ${o} ${s})`}case"hsl":{let r=Us(t.r,t.g,t.b),o=Math.round(r.h*10)/10,s=Math.round(r.s*1e3)/10,a=Math.round(r.l*1e3)/10;return t.alpha!==void 0?`hsl(${o} ${s}% ${a}% / ${t.alpha})`:`hsl(${o} ${s}% ${a}%)`}case"oklch":{let r=Pn(t),o=Math.round(r.L*1e3)/1e3,s=Math.round(r.C*1e3)/1e3,a=Math.round(r.H*10)/10;return t.alpha!==void 0?`oklch(${o} ${s} ${a} / ${t.alpha})`:`oklch(${o} ${s} ${a})`}default:throw new Error(`Unknown color format: ${i}`)}},colorMix(e,n,t=.5){let i=hd(e),r=hd(n);t=Math.max(0,Math.min(1,t));let o=i.C<1e-6,s=r.C<1e-6,a;if(o&&s)a=i.H;else if(o)a=r.H;else if(s)a=i.H;else{let d=r.H-i.H;d>180&&(d-=360),d<-180&&(d+=360),a=i.H+d*t,a<0&&(a+=360),a>=360&&(a-=360)}let u=i.L+(r.L-i.L)*t,l=i.C+(r.C-i.C)*t,c=i.alpha??1,f=r.alpha??1,p=br(c+(f-c)*t);return p!==void 0?[u,l,a,p]:[u,l,a]},colorContrast(e,n){return Kl(mo(e),mo(n))},contrastingColor(e,n,t){let i=mo(e);return Vb(n!==void 0&&t!==void 0?nc({bg:i,fg1:mo(n),fg2:mo(t)}):nc(i))},colorToColorspace(e,n){let t=mo(e),i=t.alpha,r;switch(n.toLowerCase()){case"rgb":r=[t.r/255,t.g/255,t.b/255];break;case"hsl":{let o=Us(t.r,t.g,t.b);r=[o.h,o.s,o.l];break}case"oklch":{let o=Pn(t);r=[o.L,o.C,o.H];break}case"oklab":case"lab":{let o=ec(t);r=[o.L,o.a,o.b];break}default:throw new Error(`Unknown color space: ${n}`)}return i!==void 0&&r.push(i),r},colormap(e,n){let i={...eb,...Kh,...Xh}[e];if(!i)throw new Error(`Unknown palette: ${e}`);let r=i.map(s=>Vb(Pt(s)));if(n===void 0)return r;if(Number.isInteger(n)&&n>=2){let s=n,a=[];for(let u=0;u<s;u++){let l=s===1?0:u/(s-1);a.push(this._interpolatePalette(r,l))}return a}let o=Math.max(0,Math.min(1,n));return this._interpolatePalette(r,o)},_interpolatePalette(e,n){if(e.length===0)return[0,0,0];if(n<=0)return[...e[0]];if(n>=1)return[...e[e.length-1]];let t=n*(e.length-1),i=Math.floor(t),r=t-i;if(r===0||i>=e.length-1)return[...e[Math.min(i,e.length-1)]];let[o,s,a]=e[i],[u,l,c]=e[i+1],f=s<1e-6,p=l<1e-6,d;if(f&&p)d=a;else if(f)d=c;else if(p)d=a;else{let g=c-a;g>180&&(g-=360),g<-180&&(g+=360),d=a+g*r,d<0&&(d+=360),d>=360&&(d-=360)}return[o+(u-o)*r,s+(l-s)*r,d]},colorFromColorspace(e,n){let t=e[0],i=e[1],r=e[2],o=e.length>=4?e[3]:void 0,s;switch(n.toLowerCase()){case"rgb":s=Pn({r:t*255,g:i*255,b:r*255});break;case"hsl":{let a=Gs(t,i,r);s=Pn(a);break}case"oklch":s={L:t,C:i,H:r};break;case"oklab":case"lab":s=Zs({L:t,a:i,b:r});break;default:throw new Error(`Unknown color space: ${n}`)}return o!==void 0?[s.L,s.C,s.H,o]:[s.L,s.C,s.H]},rgb(e,n,t,i){let r=Pn({r:e*255,g:n*255,b:t*255}),o=br(i);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]},hsv(e,n,t,i){let r=Hp(e,n,t),o=Pn(r),s=br(i);return s!==void 0?[o.L,o.C,o.H,s]:[o.L,o.C,o.H]},hsl(e,n,t,i){let r=Gs(e,n,t),o=Pn({r:r.r,g:r.g,b:r.b}),s=br(i);return s!==void 0?[o.L,o.C,o.H,s]:[o.L,o.C,o.H]},oklab(e,n,t,i){let r=Zs({L:e,a:n,b:t}),o=br(i);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]},oklch(e,n,t,i){let r=br(i);return r!==void 0?[e,n,t,r]:[e,n,t]},asRgb(e){let n=mo(e),t=n.r/255,i=n.g/255,r=n.b/255;return n.alpha!==void 0?[t,i,r,n.alpha]:[t,i,r]},asHsv(e){let n=mo(e),t=Wh(n.r,n.g,n.b);return n.alpha!==void 0?[t.h,t.s,t.v,n.alpha]:[t.h,t.s,t.v]},asHsl(e){let n=mo(e),t=Us(n.r,n.g,n.b);return n.alpha!==void 0?[t.h,t.s,t.l,n.alpha]:[t.h,t.s,t.l]},asOklab(e){let n=hd(e),t=Zi({L:n.L,C:n.C,H:n.H});return n.alpha!==void 0?[t.L,t.a,t.b,n.alpha]:[t.L,t.a,t.b]},colorDelta(e,n){let t=Zi(hd(e)),i=Zi(hd(n));return Qh(t,i)},distance(e,n){if(!Array.isArray(e)||!Array.isArray(n))throw new Error("Distance: expected two arrays");if(e.length!==n.length)throw new Error("Distance: dimension mismatch");let t=0;for(let i=0;i<e.length;i++){let r=e[i]-n[i];t+=r*r}return Math.sqrt(t)}};function Jb(e,...n){let t=-1;for(let r of n)Array.isArray(r)&&(t=t<0?r.length:Math.min(t,r.length));if(t<0)return e(...n);let i=new Array(t);for(let r=0;r<t;r++)i[r]=Jb(e,...n.map(o=>Array.isArray(o)?o[r]:o));return i}function CS(e,n){let t=Array.isArray(e?.[0]),i=Array.isArray(n?.[0]);if(!t&&!i){if(e.length!==n.length)return NaN;let u=0;for(let l=0;l<e.length;l++)u+=e[l]*n[l];return u}if(t&&!i)return e.map(u=>u.length===n.length?u.reduce((l,c,f)=>l+c*n[f],0):NaN);if(!t&&i){if(e.length!==n.length)return NaN;let u=n[0].length,l=new Array(u).fill(0);for(let c=0;c<e.length;c++)for(let f=0;f<u;f++)l[f]+=e[c]*n[c][f];return l}let r=e.length,o=e[0].length;if(n.length!==o)return NaN;let s=n[0].length,a=[];for(let u=0;u<r;u++){let l=new Array(s).fill(0);for(let c=0;c<o;c++){let f=e[u][c];for(let p=0;p<s;p++)l[p]+=f*n[c][p]}a.push(l)}return a}function PY(...e){let n=[],t=1;for(let r of e)Array.isArray(r)?n.push(r):t*=r;if(n.length===0)return t;let i=n[0];for(let r=1;r<n.length;r++){let o=n[r],s=!Array.isArray(i[0]),a=!Array.isArray(o[0]);if(s&&a){if(i.length!==o.length)return NaN;let u=new Array(i.length);for(let l=0;l<i.length;l++)u[l]=i[l]*o[l];i=u}else{let u=CS(i,o);if(typeof u=="number")return u;i=u}}return t!==1&&(i=Jb(r=>r*t,i)),i}function gc(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);if(i&&r){if(e.length!==n.length)return!1;for(let u=0;u<e.length;u++)if(gc(e[u],n[u],t)!==!0)return!1;return!0}if(i)return e.map(u=>gc(u,n,t));if(r)return n.map(u=>gc(e,u,t));let o=u=>typeof u=="object"&&u!==null&&"re"in u?u:{re:u,im:0},s=o(e),a=o(n);return Math.hypot(s.re-a.re,s.im-a.im)<=t}function IS(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);return i&&r?gc(e,n,t)!==!0:i?e.map(o=>IS(o,n,t)):r?n.map(o=>IS(e,o,t)):gc(e,n,t)!==!0}function iO(e){let n=e?.length;if(!n||e.some(i=>!Array.isArray(i)||i.length!==n))return NaN;let t=e.map((i,r)=>[...i,...Array.from({length:n},(o,s)=>r===s?1:0)]);for(let i=0;i<n;i++){let r=i;for(let s=i+1;s<n;s++)Math.abs(t[s][i])>Math.abs(t[r][i])&&(r=s);if(t[r][i]===0)return NaN;r!==i&&([t[i],t[r]]=[t[r],t[i]]);let o=t[i][i];for(let s=0;s<2*n;s++)t[i][s]/=o;for(let s=0;s<n;s++){if(s===i)continue;let a=t[s][i];if(a!==0)for(let u=0;u<2*n;u++)t[s][u]-=a*t[i][u]}}return t.map(i=>i.slice(n))}function DY(e){let n=t=>t&&typeof t=="object"&&"im"in t?{re:t.re,im:-t.im}:t;return Array.isArray(e)?Array.isArray(e[0])?e[0].map((t,i)=>e.map(r=>n(r[i]))):e.map(n):e}function OY(e){if(!Array.isArray(e))return NaN;if(Array.isArray(e[0])){let t=Math.min(e.length,e[0].length),i=[];for(let r=0;r<t;r++)i.push(e[r][r]);return i}let n=e.length;return Array.from({length:n},(t,i)=>Array.from({length:n},(r,o)=>i===o?e[i]:0))}function LY(e,n){if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let t=e.length;if(e.some(s=>!Array.isArray(s)||s.length!==t))return NaN;if(!Number.isInteger(n))return NaN;let i=e.map(s=>s.slice()),r=n;if(r<0){let s=iO(e);if(!Array.isArray(s))return NaN;i=s,r=-r}let o=Array.from({length:t},(s,a)=>Array.from({length:t},(u,l)=>a===l?1:0));for(let s=0;s<r;s++)o=CS(o,i);return o}function FY(e){if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let n=e.length,t=e[0].length,i=e.map(o=>o.slice()),r=0;for(let o=0;o<t&&r<n;o++){let s=r;for(let u=r+1;u<n;u++)Math.abs(i[u][o])>Math.abs(i[s][o])&&(s=u);if(i[s][o]===0)continue;s!==r&&([i[s],i[r]]=[i[r],i[s]]);let a=i[r][o];for(let u=0;u<t;u++)i[r][u]/=a;for(let u=0;u<n;u++){if(u===r)continue;let l=i[u][o];if(l!==0)for(let c=0;c<t;c++)i[u][c]-=l*i[r][c]}r++}return i}var rO={bcast:Jb,add:(e,n)=>Jb((t,i)=>t+i,e,n),chop:Jc,factorial:Vc,factorial2:ga,gamma:Me,gcd:qc,pow:(e,n)=>e===0&&n===0?NaN:Math.pow(e,n),cond:e=>{if(e===!0||e===!1)return e;throw new Error('Condition must evaluate to "True" or "False".')},heaviside:e=>e<0?0:e===0?.5:1,shuffle:(e,n)=>{let t=n===void 0?Math.random:dp(n>>>0),i=e.slice();for(let r=i.length-1;r>0;r--){let o=Math.floor(t()*(r+1));[i[r],i[o]]=[i[o],i[r]]}return i},matmul:CS,mul:PY,eq:gc,neq:IS,cross:(e,n)=>e.length===3&&n.length===3?[e[1]*n[2]-e[2]*n[1],e[2]*n[0]-e[0]*n[2],e[0]*n[1]-e[1]*n[0]]:NaN,norm:(e,n)=>{if(typeof e=="number")return Math.abs(e);if(!Array.isArray(e))return NaN;if(Array.isArray(e[0])&&n!==void 0){let r=e;if(n===1){let o=0;for(let s=0;s<r[0].length;s++){let a=0;for(let u=0;u<r.length;u++)a+=Math.abs(r[u][s]);o=Math.max(o,a)}return o}if(n===1/0){let o=0;for(let s of r){let a=0;for(let u of s)a+=Math.abs(u);o=Math.max(o,a)}return o}return NaN}let t=e.flat(1/0);if(n===1/0){let r=0;for(let o of t)r=Math.max(r,Math.abs(o));return r}if(n===void 0||n===2){let r=0;for(let o of t)r+=o*o;return Math.sqrt(r)}let i=0;for(let r of t)i+=Math.pow(Math.abs(r),n);return Math.pow(i,1/n)},transpose:e=>!Array.isArray(e)||!Array.isArray(e[0])?e:e[0].map((n,t)=>e.map(i=>i[t])),det:e=>{let n=e?.length;if(!n||e.some(r=>!Array.isArray(r)||r.length!==n))return NaN;let t=e.map(r=>r.slice()),i=1;for(let r=0;r<n;r++){let o=r;for(let s=r+1;s<n;s++)Math.abs(t[s][r])>Math.abs(t[o][r])&&(o=s);if(t[o][r]===0)return 0;o!==r&&([t[r],t[o]]=[t[o],t[r]],i=-i),i*=t[r][r];for(let s=r+1;s<n;s++){let a=t[s][r]/t[r][r];for(let u=r;u<n;u++)t[s][u]-=a*t[r][u]}}return i},inv:iO,conjTranspose:DY,diagonal:OY,matpow:LY,rref:FY,trace:e=>{if(!Array.isArray(e)||!Array.isArray(e[0]))return NaN;let n=0;for(let t=0;t<Math.min(e.length,e[0].length);t++){if(typeof e[t][t]!="number")return NaN;n+=e[t][t]}return n},shape:e=>{let n=[],t=e;for(;Array.isArray(t);)n.push(t.length),t=t[0];return n},reshape:(e,n)=>{let t=e.flat(1/0);if(t.length===0)return NaN;let i=r=>t[r%t.length];return n.length===1?Array.from({length:Math.max(0,n[0])},(r,o)=>i(o)):n.length===2?Array.from({length:Math.max(0,n[0])},(r,o)=>Array.from({length:Math.max(0,n[1])},(s,a)=>i(o*n[1]+a))):NaN},at:(e,n)=>{if(!Array.isArray(e))return NaN;let t=e.length,i=n>0?n-1:t+n;return n===0||i<0||i>=t?NaN:e[i]},integrate:(e,n,t)=>{let i=Ya(e,n,t);return i.converged?i.estimate:jl(e,n,t,1e7).estimate},integrateMC:(e,n,t)=>jl(e,n,t,1e7).estimate,lcm:Ud,lngamma:Nn,limit:wo,mean:hb,median:ou,variance:rc,populationVariance:oc,standardDeviation:LD,populationStandardDeviation:FD,kurtosis:bb,skewness:yb,mode:xb,quartiles:ad,interquartileRange:_b,covariance:Eb,populationCovariance:vb,correlation:Sb,erf:Zo,erfc:Uo,erfInv:xl,beta:ng,gammaQ:bl,betaRegularized:yl,digamma:El,trigamma:vl,polygamma:eg,zeta:Vr,lambertW:tg,besselJ:qr,besselY:gl,besselI:zo,besselK:ig,airyAi:ag,airyBi:ug,airyAiPrime:lg,airyBiPrime:cg,sinc:fg,fresnelS:Jr,fresnelC:jr,sinIntegral:gg,cosIntegral:hg,expIntegralEi:Go,logIntegral:bg,erfi:dg,agm:Xf,ellipticK:ep,ellipticE:np,ellipticEIncomplete:rp,ellipticF:ip,ellipticPiComplete:op,ellipticPiIncomplete:sp,hypergeometric2F1:ap,hypergeometric1F1:up,mandelbrot:(e,n)=>{let t=0,i=0,r=typeof e=="number"?e:e.re,o=typeof e=="number"?0:e.im,s=Math.round(n);for(let a=0;a<s;a++){let u=t*t-i*i+r;i=2*t*i+o,t=u;let l=t*t+i*i;if(l>4){let c=(a-Math.log2(Math.log2(l))+4)/s;return Math.max(0,Math.min(1,c))}}return 1},julia:(e,n,t)=>{let i=typeof e=="number"?e:e.re,r=typeof e=="number"?0:e.im,o=typeof n=="number"?n:n.re,s=typeof n=="number"?0:n.im,a=Math.round(t);for(let u=0;u<a;u++){let l=i*i-r*r+o;r=2*i*r+s,i=l;let c=i*i+r*r;if(c>4){let f=(u-Math.log2(Math.log2(c))+4)/a;return Math.max(0,Math.min(1,f))}}return 1},binomial:cl,fibonacci:MS,csin:e=>dn(new L(e.re,e.im).sin()),ccos:e=>dn(new L(e.re,e.im).cos()),ctan:e=>dn(new L(e.re,e.im).tan()),casin:e=>dn(new L(e.re,e.im).asin()),cacos:e=>dn(new L(e.re,e.im).acos()),catan:e=>dn(new L(e.re,e.im).atan()),csinh:e=>dn(new L(e.re,e.im).sinh()),ccosh:e=>dn(new L(e.re,e.im).cosh()),ctanh:e=>dn(new L(e.re,e.im).tanh()),csqrt:e=>dn(new L(e.re,e.im).sqrt()),cexp:e=>dn(new L(e.re,e.im).exp()),cln:e=>dn(new L(e.re,e.im).log()),cpow:(e,n)=>{let t=typeof e=="number"?new L(e,0):new L(e.re,e.im),i=typeof n=="number"?new L(n,0):new L(n.re,n.im);return dn(t.pow(i))},ccot:e=>dn(new L(e.re,e.im).cot()),csec:e=>dn(new L(e.re,e.im).sec()),ccsc:e=>dn(new L(e.re,e.im).csc()),ccoth:e=>dn(new L(e.re,e.im).coth()),csech:e=>dn(new L(e.re,e.im).sech()),ccsch:e=>dn(new L(e.re,e.im).csch()),cacot:e=>dn(new L(e.re,e.im).acot()),casec:e=>dn(new L(e.re,e.im).asec()),cacsc:e=>dn(new L(e.re,e.im).acsc()),cacoth:e=>dn(new L(e.re,e.im).acoth()),casech:e=>dn(new L(e.re,e.im).asech()),cacsch:e=>dn(new L(e.re,e.im).acsch()),cabs:e=>new L(e.re,e.im).abs(),carg:e=>new L(e.re,e.im).arg(),cconj:e=>dn(new L(e.re,e.im).conjugate()),cneg:e=>({re:-e.re,im:-e.im}),...RY},TS=class extends Function{SYS=rO;constructor(n,t=""){return super("_SYS","_",t?`${t};return ${n}`:`return ${n}`),new Proxy(this,{apply:(i,r,o)=>super.apply(r,[this.SYS,...o]),get:(i,r)=>r==="toString"?()=>n:r==="isCompiled"?!0:Reflect.get(i,r)})}},jb=class extends Function{SYS=rO;constructor(n,t,i=""){return super("_SYS",...t,i?`${i}return ${n}`:`return ${n}`),new Proxy(this,{apply:(r,o,s)=>super.apply(o,[this.SYS,...s]),get:(r,o)=>o==="toString"?()=>i?`(${t.join(", ")}) => { ${i}return ${n}; }`:`(${t.join(", ")}) => ${n}`:o==="isCompiled"?!0:Reflect.get(r,o)})}},hc=class{getOperators(){return SS}getFunctions(){return NS}createTarget(n={}){return{language:"javascript",operators:t=>SS[t],functions:t=>NS[t],var:t=>({Pi:"Math.PI",ExponentialE:"Math.E",NaN:"Number.NaN",ImaginaryUnit:"({ re: 0, im: 1 })",Half:"0.5",MachineEpsilon:"Number.EPSILON",GoldenRatio:"((1 + Math.sqrt(5)) / 2)",CatalanConstant:"0.91596559417721901",EulerGamma:"0.57721566490153286"})[t],string:t=>JSON.stringify(t),number:t=>t.toString(),complex:(t,i)=>`({ re: ${t}, im: ${i} })`,bindExpr:(t,i)=>`((${t.map(r=>r[0]).join(", ")}) => ${i})(${t.map(r=>r[1]).join(", ")})`,assertBoolean:t=>`_SYS.cond(${t})`,indent:0,ws:t=>t??"",preamble:"",...n}}compile(n,t={}){try{return this.compileOrThrow(n,t)}catch(i){if(t.fallback!==!0)throw i;let r=i.message;return console.warn(`Compilation fallback for "${n.operator}" (target: javascript): ${r}`),D.buildInterpreterFallback(n,r,"javascript",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=po(n);let{operators:i,functions:r,vars:o,imports:s=[],preamble:a,realOnly:u,iterationBudget:l,quadrature:c}=t,f=n.unknowns,p=s.map(y=>{if(typeof y=="function")return y.toString();throw new Error(`Unsupported import \`${y}\``)}).join(`
|
|
141
141
|
`),d={};if(r)for(let[y,x]of Object.entries(r))typeof x=="function"?JY(x)?(p+=`${x.toString()};
|
|
142
142
|
`,d[y]=x.name):(p+=`const ${y} = ${x.toString()};
|
|
143
143
|
`,d[y]=y):typeof x=="string"&&(d[y]=x);let g=y=>{if(i){let x=typeof i=="function"?i(y):i[y];if(x)return x}return SS[y]},h=this.createTarget({operators:g,functions:y=>d?.[y]?d[y]:NS[y],var:y=>{if(o&&y in o){let E=o[y];return typeof E=="string"?E:JSON.stringify(E)}let x={Pi:"Math.PI",ExponentialE:"Math.E",NaN:"Number.NaN",ImaginaryUnit:"({ re: 0, im: 1 })",Half:"0.5",MachineEpsilon:"Number.EPSILON",GoldenRatio:"((1 + Math.sqrt(5)) / 2)",CatalanConstant:"0.91596559417721901",EulerGamma:"0.57721566490153286"}[y];if(x!==void 0)return x;if(f.includes(y))return`_.${y}`;if(n.engine._getSymbolValue(y)===void 0)return`_.${y}`},preamble:(a??"")+p,iterationBudget:l,quadrature:c,varsKeys:o?new Set(Object.keys(o)):void 0,randomSeed:n.engine._randomNumericSeed(),randomState:{counter:0},userFunctions:{defs:new Map,compiling:new Set}}),b=BY(n,h,u);return D.withReferences(b,n,h,o?new Set(Object.keys(o)):void 0)}};function wS(e){let n=e.run;return{...e,run:((...i)=>{let r=n(...i);return typeof r=="boolean"?NaN:typeof r=="object"&&r!==null&&"im"in r?r.im===0?r.re:NaN:r})}}function BY(e,n,t){if(m(e,"Function")){let u=e.ops,l=u.slice(1).map(g=>cn(g)||"_"),c=D.compile(u[0].canonical,{...n,var:g=>l.includes(g)?g:n.var(g),boundVars:D.withBoundNames(n,l)}),f=D.userFunctionsPreamble(n),p=new jb(c,l,f),d={target:"javascript",success:!0,code:f?`(${l.join(", ")}) => { ${f}return ${c}; }`:`(${l.join(", ")}) => ${c}`,calling:"lambda",run:p};return t?wS(d):d}if(w(e)){let u=n.operators?.(e.symbol);if(u){let l=new jb(`a ${u[0]} b`,["a","b"]),c={target:"javascript",success:!0,code:`(a, b) => a ${u[0]} b`,calling:"lambda",run:l};return t?wS(c):c}}let i=D.compile(e,n),r=D.userFunctionsPreamble(n),o=r?n.preamble?`${n.preamble}
|
|
144
|
-
${r}`:r:n.preamble,s=new TS(i,o),a={target:"javascript",success:!0,code:i,calling:"expression",run:s};return t?wS(a):a}var $Y=100;function oO(e){e.operator;let n=e,t=w(n.op1)?n.op1.symbol:"_",i=n.op2,r=n.op3,o=i.re,s=r.re;return{index:t,lowerExpr:i,upperExpr:r,lowerNum:!isNaN(o)&&Number.isFinite(o)?Math.floor(o):void 0,upperNum:!isNaN(s)&&Number.isFinite(s)?Math.floor(s):void 0}}function Y6(e,n,t){return n!==void 0?String(n):`Math.floor(${D.compile(e,t)})`}function W6(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1]){if(go(n[0]))return nO(e,n[0],i,!1);if(tO(n[0]))return nO(e,n[0],i,!0);throw new Error(`${e}: no indexing set`)}return sO(e,n[0],n.slice(1),i)}function ve(e,n,t,i){if(!n||!go(n))throw new Error(`${e}: ${i!==void 0?`operand ${i}`:"operand"} is not an indexed collection (list/vector/range). Fail closed (D6).`);return t(n)}function Q6(e){if(w(e))switch(e.symbol){case"Add":return"(_a, _b) => _a + _b";case"Multiply":return"(_a, _b) => _a * _b";case"Min":return"(_a, _b) => Math.min(_a, _b)";case"Max":return"(_a, _b) => Math.max(_a, _b)"}}function K6(e,n,t){let i=!1;if(m(e,"Function"))i=e.nops-1===2;else if(w(e)){let r=D.userFunctionLiteral(e.engine,e.symbol);r!==void 0?i=r.nops-1===2:i=t.operators?.(e.symbol)!==void 0}if(i)return`((_f) => (_a, _b) => _f(_a, _b))(${n(e)})`}function du(e,n){let t=De(n.type.type);if(!(t!==void 0&&(t==="number"||$(t,"real")||$(t,"boolean")||$(t,"string"))&&!D.isComplexValued(n)))throw new Error(`${e}: cannot compile \u2014 the interpreter compares elements structurally, but only real/boolean/string elements compare by value on the JavaScript target. Fail closed (D6).`)}function X6(e,n,t){let i=e==="Max"?"Math.max":"Math.min",r=e==="Max"?"-Infinity":"Infinity";return n.length===1&&n[0]&&go(n[0])?`(${t(n[0])}).reduce((_a, _b) => ${i}(_a, _b), ${r})`:n.some(o=>o&&go(o))?`[${n.map(s=>go(s)?`...(${t(s)})`:t(s)).join(", ")}].reduce((_a, _b) => ${i}(_a, _b), ${r})`:`${i}(${n.map(o=>t(o)).join(", ")})`}function eO(e,n,t){let i=e==="GCD"?"_SYS.gcd":"_SYS.lcm",r=e==="GCD"?"0":"1",o=n.map(s=>{if(go(s))return`...(${t(s)})`;if(s.isCollection||s.type.matches("collection"))throw new Error(`${e}: cannot compile \u2014 operand is a collection but not an indexed collection (list/vector/range). Fail closed (D6).`);return t(s)});return`((_a) => _a.length ? _a.reduce((_x, _y) => ${i}(_x, _y)) : ${r})([${o.join(", ")}])`}function nO(e,n,t,i){let r=D.compile(n,t);return i?`((_c) => Array.isArray(_c) ? _c.reduce((_a, _b) => ${e==="Sum"?"_SYS.add":"_SYS.mul"}(_a, _b), ${e==="Sum"?"0":"1"}) : _c)(${r})`:`(${r}).reduce((_a, _b) => _a ${e==="Sum"?"+":"*"} _b, ${e==="Sum"?"0":"1"})`}function sO(e,n,t,i){D.assertScalarBigOpBody(e,n);let{index:r,lowerExpr:o,upperExpr:s,lowerNum:a,upperNum:u}=oO(t[0]),l=t.slice(1),c=e==="Sum",f=c?"+":"*",p=c?"0":"1",d=D.isComplexValued(n),g=I=>l.length>0?sO(e,n,l,I):D.compile(n,I),h=a!==void 0&&u!==void 0;if(h&&a>u)return p;if(h&&u-a+1<=$Y){let T=[];for(let O=a;O<=u;O++){let J={...i,var:G=>G===r?String(O):i.var(G),boundVars:D.withBoundNames(i,[r])};T.push(`(${g(J)})`)}if(!d)return`(${T.join(` ${f} `)})`;let k=T.map((O,J)=>`_t${J}`),A=T.map((O,J)=>`const ${k[J]} = ${O}`).join("; ");if(c){let O=k.map(G=>`${G}.re`).join(" + "),J=k.map(G=>`${G}.im`).join(" + ");return`(() => { ${A}; return { re: ${O}, im: ${J} }; })()`}let P=k[0],B=[A];for(let O=1;O<k.length;O++){let J=P;P=`_p${O}`,B.push(`const ${P} = { re: ${J}.re * ${k[O]}.re - ${J}.im * ${k[O]}.im, im: ${J}.re * ${k[O]}.im + ${J}.im * ${k[O]}.re }`)}return`(() => { ${B.join("; ")}; return ${P}; })()`}let b=Y6(o,a,i),y=Y6(s,u,i),x=g({...i,var:I=>I===r?r:i.var(I),boundVars:D.withBoundNames(i,[r])}),E=D.tempVar(),v=i.iterationBudget,_=I=>v!==void 0?`if (!(_upper - ${r} < ${v})) return ${I}; `:"";if(d){let I=D.tempVar(),T=_("{ re: NaN, im: NaN }");return c?`(() => { let ${E} = { re: 0, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${T}while (${r} <= _upper) { const ${I} = ${x}; ${E} = { re: ${E}.re + ${I}.re, im: ${E}.im + ${I}.im }; ${r}++; } return ${E}; })()`:`(() => { let ${E} = { re: 1, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${T}while (${r} <= _upper) { const ${I} = ${x}; ${E} = { re: ${E}.re * ${I}.re - ${E}.im * ${I}.im, im: ${E}.re * ${I}.im + ${E}.im * ${I}.re }; ${r}++; } return ${E}; })()`}return`(() => { let ${E} = ${p}; let ${r} = ${b}; const _upper = ${y}; ${_("NaN")}while (${r} <= _upper) { ${E} ${f}= ${x}; ${r}++; } return ${E}; })()`}function qY(e,n){let t=n.varsKeys;if(!t||t.size===0)return!1;for(let i of t)if(e.some(r=>r.has(i)))return!0;return!1}function VY(e,n,t){if(!qY(e,t))try{let p=e[0].engine._fn("Integrate",[...e]).evaluate();if(!p.has("Integrate")&&p.isValid&&p.isNaN!==!0)return`(${n(p)})`}catch{}let{index:i,lowerExpr:r,upperExpr:o}=oO(e[1]),s=i,a=e[0];if(m(e[0],"Function")){let p=cn(e[0].ops[1]);p&&(s=p),a=e[0].ops[0]}let u=D.compile(a,{...t,var:p=>p===s?p:t.var(p),boundVars:D.withBoundNames(t,[s])}),l=D.compile(r,t),c=D.compile(o,t);return`${t.quadrature==="monte-carlo"?"_SYS.integrateMC":"_SYS.integrate"}((${s}) => (${u}), ${l}, ${c})`}function JY(e){let n=e.toString();return n.includes("=>")?!1:n.startsWith("function ")&&n.includes(e.name)}function MS(e){if(!Number.isInteger(e))return NaN;if(e<0)return e%2===0?-MS(-e):MS(-e);if(e<=1)return e;let n=0,t=1;for(let i=2;i<=e;i++){let r=n+t;n=t,t=r}return t}var aO={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],Divide:["/",13],Equal:["==",8],NotEqual:["!=",8],LessEqual:["<=",9],GreaterEqual:[">=",9],Less:["<",9],Greater:[">",9],And:["&&",4],Or:["||",3],Not:["!",14]},jY=new Set(["attribute","const","uniform","varying","buffer","shared","coherent","volatile","restrict","readonly","writeonly","layout","centroid","flat","smooth","noperspective","patch","sample","in","out","inout","precision","invariant","precise","subroutine","break","continue","do","for","while","switch","case","default","if","else","discard","return","void","bool","int","uint","float","double","vec2","vec3","vec4","dvec2","dvec3","dvec4","bvec2","bvec3","bvec4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","sampler2D","sampler3D","samplerCube","sampler2DArray","sampler2DShadow","samplerCubeShadow","isampler2D","usampler2D","atomic_uint","image2D","true","false","filter","texture","asm","union","enum","typedef","template","this","packed","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sizeof","cast","namespace","using"]),zY=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","bool","f16","f32","i32","u32","vec2","vec3","vec4","vec2f","vec3f","vec4f","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","array","atomic","ptr","sampler","sampler_comparison","texture_1d","texture_2d","texture_2d_array","texture_3d","texture_cube","texture_cube_array","texture_multisampled_2d","function","private","workgroup","uniform","storage","read","write","read_write","texture","sample","filter","as","async","attribute","auto","binding","cast","compile","do","enum","extern","external","inline","instance","interface","match","namespace","new","null","of","operator","public","reference","self","set","shared","static","super","template","this","typedef","union","unless","using","virtual","where"]);function GY(e){return e==="wgsl"?zY:e==="glsl"?jY:new Set}function OS(e,n){if(GY(n).has(e))throw new Error(`"${e}" is a reserved word in ${n??"this shader language"} and cannot be used as a variable name. Rename it before compiling to a GPU target (fail closed, D6).`);return e}function Hi(e){return e?.language==="wgsl"?"vec2f":"vec2"}function bc(e){return e?.language==="wgsl"?"vec3f":"vec3"}function DS(e){return e?.language==="wgsl"?"bitcast<f32>(0x7fc00000u)":"_gpu_nan()"}function cO(e){if(e===null)return;if(m(e,"Tuple")||m(e,"List")){let t=e.nops;return t>=2&&t<=4?t:void 0}if(D.isComplexValued(e))return 2;let n=e.type.type;if(typeof n!="string"){if(n.kind==="tuple"){let t=n.elements.length;return t>=2&&t<=4?t:void 0}if(n.kind==="list"&&n.dimensions?.length===1){let t=n.dimensions[0];return t>=2&&t<=4?t:void 0}}}function kS(e,n){let t=cO(e);return t===void 0?DS(n):`${n?.language==="wgsl"?`vec${t}f`:`vec${t}`}(${DS(n)})`}function bd(e,n,t,i){return i?.language==="wgsl"?`select(${t}, ${n}, ${e})`:`((${e}) ? (${n}) : (${t}))`}function zb(e,n,t){if(n.length===0)throw new Error(`${e}: needs at least one argument`);if(n.length===1)return t(n[0]);let i=`${e}(${t(n[0])}, ${t(n[1])})`;for(let r=2;r<n.length;r++)i=`${e}(${i}, ${t(n[r])})`;return i}function AS(e,n,t){let i=e.type.type;if(!(typeof i!="string"&&i.kind==="tuple")&&e.type.matches("indexed_collection"))throw new Error(`Point${n.toUpperCase()}: a list of points has no GPU lowering (a point must be a single vec2/vec3/vec4). Fail closed.`);return`${t(e)}.${n}`}function RS(e){return q(e)?e.string?.toLowerCase()??null:null}function uO(e,n,t){let i=Qe(e);return i!==void 0&&Number.isInteger(i)?i.toString():`${t?.language==="wgsl"?"i32":"int"}(${n(e)})`}var UY=100,ZY=4;function lO(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(D.assertScalarBigOpBody(e,n[0]),D.isComplexValued(n[0]))throw new Error(`${e}: complex-valued body not supported in GPU targets`);if(n.length>2)throw new Error(`${e}: multi-index (${n.length-1} indexing sets) is not supported in GPU targets`);let r=n[1];if(!m(r,"Limits"))throw new Error(`${e}: expected Limits indexing set`);let o=r.ops,s=w(o[0])?o[0].symbol:"_",a=o[1].re,u=o[2].re,l=!isNaN(a)&&Number.isFinite(a)?Math.floor(a):void 0,c=!isNaN(u)&&Number.isFinite(u)?Math.floor(u):void 0,f=e==="Sum",p=f?"+":"*",d=f?"0.0":"1.0",g=i.language==="wgsl",h=l!==void 0&&c!==void 0;if(h&&l>c)return d;if(h&&c-l+1<=UY){let P=[];for(let B=l;B<=c;B++){let O=oa(B),J={...i,var:G=>G===s?O:i.var(G)};P.push(`(${D.compile(n[0],J)})`)}return`(${P.join(` ${p} `)})`}let b=D.tempVar(),y=g?"f32":"float",x=g?"i32":"int",E={...i,var:P=>P===s?g?`f32(${s})`:`float(${s})`:i.var(P)},v=D.compile(n[0],E),_=l!==void 0?String(l):D.compile(o[1],i),I=c!==void 0?String(c):D.compile(o[2],i);OS(s,i.language);let T=g?`var ${b}: ${y}`:`${y} ${b}`,k=g?`var ${s}: ${x}`:`${x} ${s}`;return[`${T} = ${d};`,`for (${k} = ${_}; ${s} <= ${I}; ${s}++) {`,` ${b} ${p}= ${v};`,"}",`return ${b};`].join(`
|
|
145
|
-
`)}var HY={Add:(e,n,t)=>{if(e.length===0)return"0.0";if(e.length===1)return n(e[0]);if(!e.some(l=>D.isComplexValued(l)))return ra(e.map(l=>n(l)),"0.0","+");let r=e.map(l=>Z6(l,n));if(r.some(l=>l===null)){let l=Hi(t);return e.map(c=>{let f=n(c);return D.isComplexValued(c)?f:`${l}(${f}, 0.0)`}).join(" + ")}let o=[],s=[];for(let l of r)l.re!==null&&o.push(l.re),l.im!==null&&s.push(l.im);let a=ra(o,"0.0","+"),u=ra(s,"0.0","+");return`${Hi(t)}(${a}, ${u})`},Multiply:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);if(!e.some(l=>D.isComplexValued(l)))return ra(e.map(l=>n(l)),"1.0","*");let r=e.findIndex(l=>w(l,"ImaginaryUnit")||N(l)&&l.re===0&&l.im!==0);if(r>=0){let l=e[r],c=w(l,"ImaginaryUnit")?1:l.im,f=e.filter((h,b)=>b!==r),p=Hi(t);if(f.length===0)return`${p}(0.0, ${Jn(c)})`;let d=f.map(h=>qb(h,n(h)));c!==1&&d.unshift(Jn(c));let g=ra(d,"1.0","*");return`${p}(0.0, ${g})`}let o=[],s=[];for(let l of e)D.isComplexValued(l)?s.push(n(l)):o.push(qb(l,n(l)));let a=ra(o,"1.0","*"),u=s[0];for(let l=1;l<s.length;l++)u=`_gpu_cmul(${u}, ${s[l]})`;return a!=="1.0"&&(u=`(${a} * ${u})`),u},Divide:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);let i=D.isComplexValued(e[0]),r=e.length>=2&&D.isComplexValued(e[1]);if(!i&&!r){if(e.length===2){let a=Qe(e[0]),u=Qe(e[1]);return a!==void 0&&u!==void 0&&u!==0?Jn(a/u):u===1?n(e[0]):`${n(e[0])} / ${n(e[1])}`}let s=n(e[0]);for(let a=1;a<e.length;a++)s=`${s} / ${n(e[a])}`;return s}return i&&r?`_gpu_cdiv(${n(e[0])}, ${n(e[1])})`:i&&!r?`(${n(e[0])} / ${n(e[1])})`:`_gpu_cdiv(${Hi(t)}(${n(e[0])}, 0.0), ${n(e[1])})`},Negate:([e],n,t)=>{if(e===null)throw new Error("Negate: no argument");let i=Qe(e);return i!==void 0?Jn(-i):N(e)&&e.im!==0?`${Hi(t)}(${Jn(-e.re)}, ${Jn(-e.im)})`:w(e,"ImaginaryUnit")?`${Hi(t)}(0.0, -1.0)`:`(-${n(e)})`},Abs:(e,n)=>D.isComplexValued(e[0])?`length(${n(e[0])})`:D.isNonNegative(e[0])?n(e[0]):`abs(${n(e[0])})`,Arccos:(e,n)=>D.isComplexValued(e[0])?`_gpu_cacos(${n(e[0])})`:`acos(${n(e[0])})`,Arcsin:(e,n)=>D.isComplexValued(e[0])?`_gpu_casin(${n(e[0])})`:`asin(${n(e[0])})`,Arctan:(e,n)=>D.isComplexValued(e[0])?`_gpu_catan(${n(e[0])})`:`atan(${n(e[0])})`,Ceil:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`ceil(${n(e[0])})`,Clamp:"clamp",Cos:(e,n)=>D.isComplexValued(e[0])?`_gpu_ccos(${n(e[0])})`:`cos(${n(e[0])})`,Degrees:"radians",Exp:(e,n)=>D.isComplexValued(e[0])?`_gpu_cexp(${n(e[0])})`:`exp(${n(e[0])})`,Exp2:"exp2",First:(e,n)=>`${n(e[0])}.x`,Second:(e,n)=>`${n(e[0])}.y`,Third:(e,n)=>`${n(e[0])}.z`,PointX:(e,n)=>AS(e[0],"x",n),PointY:(e,n)=>AS(e[0],"y",n),PointZ:(e,n)=>AS(e[0],"z",n),Floor:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`floor(${n(e[0])})`,Fract:"fract",Ln:(e,n)=>D.isComplexValued(e[0])?`_gpu_cln(${n(e[0])})`:`log(${n(e[0])})`,Log2:"log2",Max:(e,n)=>zb("max",e,n),Min:(e,n)=>zb("min",e,n),ElementMax:(e,n)=>zb("max",e,n),ElementMin:(e,n)=>zb("min",e,n),Mix:"mix",If:(e,n,t)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return bd(n(e[0]),n(e[1]),n(e[2]),t)},When:(e,n,t)=>{if(e.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");return w(e[1],"True")?`(${n(e[0])})`:w(e[1],"False")?kS(e[0],t):bd(n(e[1]),n(e[0]),kS(e[0],t),t)},Which:(e,n,t)=>{if(e.length<2||e.length%2!==0)throw new Error("Which: expected condition/value pairs");let i=e.filter((o,s)=>s%2===1).find(o=>cO(o))??null,r=o=>{if(o>=e.length)return kS(i,t);let s=e[o],a=e[o+1];return w(s,"True")?`(${n(a)})`:bd(n(s),n(a),r(o+2),t)};return r(0)},Match:(e,n,t)=>D.compileMatchTernary(e[0].engine,e,t,{ternary:(i,r,o)=>bd(i,r,o,t),eq:"==",noMatch:DS(t),allowStrings:!1}),Power:(e,n,t)=>{let i=e[0],r=e[1];if(i===null)throw new Error("Power: no argument");if(D.isComplexValued(i)||D.isComplexValued(r)){if(w(i,"ExponentialE"))return`_gpu_cexp(${n(r)})`;let a=Hi(t),u=D.isComplexValued(i)?n(i):`${a}(${n(i)}, 0.0)`,l=D.isComplexValued(r)?n(r):`${a}(${n(r)}, 0.0)`;return`_gpu_cpow(${u}, ${l})`}let o=Qe(i),s=Qe(r);if(o!==void 0&&s!==void 0)return Jn(Math.pow(o,s));if(s===0)return"1.0";if(s===1)return n(i);if(s===.5)return`sqrt(${n(i)})`;if(s!==void 0&&Number.isInteger(s)){let a=s,u=Math.abs(a),l;if(u===1)l=`(${n(i)})`;else if((w(i)||N(i))&&u<=ZY){let c=n(i);l=`(${Array(u).fill(c).join(" * ")})`}else l=`_gpu_powi(${n(i)}, ${oa(u)})`;return a<0?`(1.0 / ${l})`:l}return`pow(${n(i)}, ${n(r)})`},Radians:"radians",Round:(e,n)=>{if(D.isIntegerValued(e[0]))return n(e[0]);let t=n(e[0]);return`(sign(${t}) * floor(abs(${t}) + 0.5))`},Sign:"sign",Sin:(e,n)=>D.isComplexValued(e[0])?`_gpu_csin(${n(e[0])})`:`sin(${n(e[0])})`,Smoothstep:"smoothstep",Sqrt:(e,n)=>{if(D.isComplexValued(e[0]))return`_gpu_csqrt(${n(e[0])})`;let t=Qe(e[0]);return t!==void 0?Jn(Math.sqrt(t)):`sqrt(${n(e[0])})`},Step:"step",Tan:(e,n)=>D.isComplexValued(e[0])?`_gpu_ctan(${n(e[0])})`:`tan(${n(e[0])})`,Truncate:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`trunc(${n(e[0])})`,Real:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).x`:n(e[0]),Imaginary:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).y`:"0.0",Argument:(e,n,t)=>{if(D.isComplexValued(e[0])){let i=n(e[0]);return`atan(${i}.y, ${i}.x)`}return bd(`${n(e[0])} >= 0.0`,"0.0","3.14159265359",t)},Conjugate:(e,n,t)=>{if(D.isComplexValued(e[0])){let i=Hi(t),r=n(e[0]);return`${i}(${r}.x, -${r}.y)`}return n(e[0])},Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");return`(${t(e)} - ${t(n)} * round(${t(e)} / ${t(n)}))`},Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");if(D.isComplexValued(e))return`_gpu_cdiv(_gpu_ccos(${n(e)}), _gpu_csin(${n(e)}))`;let t=n(e);return`(cos(${t}) / sin(${t}))`},Csc:([e],n,t)=>{if(e===null)throw new Error("Csc: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_csin(${n(e)}))`:`(1.0 / sin(${n(e)}))`},Sec:([e],n,t)=>{if(e===null)throw new Error("Sec: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_ccos(${n(e)}))`:`(1.0 / cos(${n(e)}))`},Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return`(1.5707963267948966 - atan(${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return`asin(1.0 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return`acos(1.0 / (${n(e)}))`},Sinh:(e,n)=>D.isComplexValued(e[0])?`_gpu_csinh(${n(e[0])})`:`sinh(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`_gpu_ccosh(${n(e[0])})`:`cosh(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`_gpu_ctanh(${n(e[0])})`:`tanh(${n(e[0])})`,Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");if(D.isComplexValued(e))return`_gpu_cdiv(_gpu_ccosh(${n(e)}), _gpu_csinh(${n(e)}))`;let t=n(e);return`(cosh(${t}) / sinh(${t}))`},Csch:([e],n,t)=>{if(e===null)throw new Error("Csch: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_csinh(${n(e)}))`:`(1.0 / sinh(${n(e)}))`},Sech:([e],n,t)=>{if(e===null)throw new Error("Sech: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_ccosh(${n(e)}))`:`(1.0 / cosh(${n(e)}))`},Arcosh:(e,n)=>D.isComplexValued(e[0])?`_gpu_cacosh(${n(e[0])})`:`acosh(${n(e[0])})`,Arsinh:(e,n)=>D.isComplexValued(e[0])?`_gpu_casinh(${n(e[0])})`:`asinh(${n(e[0])})`,Artanh:(e,n)=>D.isComplexValued(e[0])?`_gpu_catanh(${n(e[0])})`:`atanh(${n(e[0])})`,Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return`atanh(1.0 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return`asinh(1.0 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return`acosh(1.0 / (${n(e)}))`},Arctan2:(e,n)=>{if(e.length<2)throw new Error("Arctan2: need two arguments");return`atan(${n(e[0])}, ${n(e[1])})`},Hypot:([e,n],t)=>{if(e===null||n===null)throw new Error("Hypot: need two arguments");return`length(vec2(${t(e)}, ${t(n)}))`},Haversine:([e],n)=>{if(e===null)throw new Error("Haversine: no argument");return`((1.0 - cos(${n(e)})) * 0.5)`},InverseHaversine:([e],n)=>{if(e===null)throw new Error("InverseHaversine: no argument");return`(2.0 * asin(sqrt(${n(e)})))`},Gamma:([e],n)=>{if(e===null)throw new Error("Gamma: no argument");return`_gpu_gamma(${n(e)})`},GammaLn:([e],n)=>{if(e===null)throw new Error("GammaLn: no argument");return`_gpu_gammaln(${n(e)})`},Factorial:([e],n)=>{if(e===null)throw new Error("Factorial: no argument");return`_gpu_gamma(${n(e)} + 1.0)`},Beta:([e,n],t)=>{if(e===null||n===null)throw new Error("Beta: need two arguments");let i=t(e),r=t(n);return`(_gpu_gamma(${i}) * _gpu_gamma(${r}) / _gpu_gamma(${i} + ${r}))`},Erf:([e],n)=>{if(e===null)throw new Error("Erf: no argument");return`_gpu_erf(${n(e)})`},Erfc:([e],n)=>{if(e===null)throw new Error("Erfc: no argument");return`(1.0 - _gpu_erf(${n(e)}))`},ErfInv:([e],n)=>{if(e===null)throw new Error("ErfInv: no argument");return`_gpu_erfinv(${n(e)})`},Heaviside:([e],n)=>{if(e===null)throw new Error("Heaviside: no argument");return`_gpu_heaviside(${n(e)})`},Sinc:([e],n)=>{if(e===null)throw new Error("Sinc: no argument");return`_gpu_sinc(${n(e)})`},FresnelC:([e],n)=>{if(e===null)throw new Error("FresnelC: no argument");return`_gpu_fresnelC(${n(e)})`},FresnelS:([e],n)=>{if(e===null)throw new Error("FresnelS: no argument");return`_gpu_fresnelS(${n(e)})`},BesselJ:([e,n],t,i)=>{if(e===null||n===null)throw new Error("BesselJ: need two arguments");return`_gpu_besselJ(${i?.language==="wgsl"?"i32":"int"}(${t(e)}), ${t(n)})`},Lb:"log2",Log:(e,n)=>{if(e.length===0)throw new Error("Log: no argument");return e.length===1?`(log(${n(e[0])}) / log(10.0))`:`(log(${n(e[0])}) / log(${n(e[1])}))`},Log10:([e],n)=>{if(e===null)throw new Error("Log10: no argument");return`(log(${n(e)}) * 0.4342944819032518)`},Lg:([e],n)=>{if(e===null)throw new Error("Lg: no argument");return`(log(${n(e)}) * 0.4342944819032518)`},Square:([e],n)=>{if(e===null)throw new Error("Square: no argument");if(w(e)||N(e)){let t=n(e);return`(${t} * ${t})`}return`_gpu_powi(${n(e)}, 2.0)`},Root:([e,n],t)=>{if(e===null)throw new Error("Root: no argument");if(n==null)return`sqrt(${t(e)})`;let i=Qe(n);if(i===2)return`sqrt(${t(e)})`;let r=Qe(e);if(r!==void 0&&i!==void 0){let o=Math.pow(r,1/i);return Number.isNaN(o)&&Number.isInteger(i)&&i%2!==0&&r<0?Jn(-Math.pow(-r,1/i)):Jn(o)}if(i!==void 0&&Number.isInteger(i)&&i%2!==0){let o=t(e);return`(sign(${o}) * pow(abs(${o}), ${Jn(1/i)}))`}return`pow(${t(e)}, 1.0 / ${t(n)})`},ColorMix:(e,n)=>{if(e.length<2)throw new Error("ColorMix: need two colors");let t=n(e[0]),i=n(e[1]),r=e.length>=3?n(e[2]):"0.5";return`_gpu_color_mix(${t}, ${i}, ${r})`},ColorContrast:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorContrast: need two colors");return`_gpu_apca(${t(e)}, ${t(n)})`},ContrastingColor:(e,n,t)=>{if(e.length===0)throw new Error("ContrastingColor: no argument");let i=n(e[0]);if(e.length>=3){let u=n(e[1]),l=n(e[2]);return`(abs(_gpu_apca(${i}, ${u})) >= abs(_gpu_apca(${i}, ${l})) ? ${u} : ${l})`}let o=t?.language==="wgsl"?"vec3f":"vec3",s=`${o}(0.0)`,a=`${o}(1.0, 0.0, 0.0)`;return`((_gpu_apca(${i}, ${s}) > 50.0) ? ${s} : ${a})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");let i=RS(n);if(i===null)throw new Error("ColorToColorspace: space must be a string literal");let r=t(e);switch(i){case"oklch":return r;case"oklab":case"lab":return`_gpu_oklch_to_oklab(${r})`;case"rgb":return`_gpu_oklch_to_srgb(${r})`;case"hsl":return`_gpu_rgb_to_hsl(_gpu_oklch_to_srgb(${r}))`;case"hsv":return`_gpu_rgb_to_hsv(_gpu_oklch_to_srgb(${r}))`;default:throw new Error(`ColorToColorspace: unsupported space "${i}" on GPU target`)}},ColorFromColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorFromColorspace: need components and space");let i=RS(n);if(i===null)throw new Error("ColorFromColorspace: space must be a string literal");let r=t(e);switch(i){case"oklch":return r;case"oklab":case"lab":return`_gpu_oklab_to_oklch(${r})`;case"rgb":return`_gpu_srgb_to_oklch(${r})`;case"hsl":return`_gpu_srgb_to_oklch(_gpu_hsl_to_rgb(${r}))`;case"hsv":return`_gpu_srgb_to_oklch(_gpu_hsv_to_rgb(${r}))`;default:throw new Error(`ColorFromColorspace: unsupported space "${i}" on GPU target`)}},Color:([e],n,t)=>{if(e===null)throw new Error("Color: no argument");let i=RS(e);if(i===null)throw new Error("Color: argument must be a string literal on GPU target");let r=Pt(i);if(r===0&&i.trim().toLowerCase()!=="transparent")throw new Error(`Color: invalid color string "${i}"`);let o=r>>>24&255,s=r>>>16&255,a=r>>>8&255,u=Pn({r:o,g:s,b:a});return`${bc(t)}(${Jn(u.L)}, ${Jn(u.C)}, ${Jn(u.H)})`},Rgb:(e,n,t)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_gpu_srgb_to_oklch(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])}))`},Hsv:(e,n,t)=>{if(e.length<3)throw new Error("Hsv: need 3 components");return`_gpu_srgb_to_oklch(_gpu_hsv_to_rgb(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})))`},Hsl:(e,n,t)=>{if(e.length<3)throw new Error("Hsl: need 3 components");return`_gpu_srgb_to_oklch(_gpu_hsl_to_rgb(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})))`},Oklab:(e,n,t)=>{if(e.length<3)throw new Error("Oklab: need 3 components");return`_gpu_oklab_to_oklch(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])}))`},Oklch:(e,n,t)=>{if(e.length<3)throw new Error("Oklch: need 3 components");return`${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`},AsOklch:([e],n)=>{if(e===null)throw new Error("AsOklch: no argument");return n(e)},AsOklab:([e],n)=>{if(e===null)throw new Error("AsOklab: no argument");return`_gpu_oklch_to_oklab(${n(e)})`},AsRgb:([e],n)=>{if(e===null)throw new Error("AsRgb: no argument");return`_gpu_oklch_to_srgb(${n(e)})`},AsHsv:([e],n)=>{if(e===null)throw new Error("AsHsv: no argument");return`_gpu_rgb_to_hsv(_gpu_oklch_to_srgb(${n(e)}))`},AsHsl:([e],n)=>{if(e===null)throw new Error("AsHsl: no argument");return`_gpu_rgb_to_hsl(_gpu_oklch_to_srgb(${n(e)}))`},Mandelbrot:([e,n],t,i)=>{if(e===null||n===null)throw new Error("Mandelbrot: missing arguments");let r=uO(n,t,i);return`_fractal_mandelbrot(${t(e)}, ${r})`},Julia:([e,n,t],i,r)=>{if(e===null||n===null||t===null)throw new Error("Julia: missing arguments");let o=uO(t,i,r);return`_fractal_julia(${i(e)}, ${i(n)}, ${o})`},Cross:"cross",Distance:"distance",Dot:"dot",Norm:"length",Length:(e,n,t)=>{throw new Error(`Length (collection element count) is not supported on the ${t.language??"GPU"} target: the '${t.language??"GPU"}' 'length()' builtin is the Euclidean norm (CE 'Norm'), not a count. Fail closed (D6).`)},Normalize:"normalize",Reflect:"reflect",Refract:"refract",Sum:(e,n,t)=>lO("Sum",e,n,t),Product:(e,n,t)=>lO("Product",e,n,t),Range:(e,n,t)=>{if(e.length<2||e.length>3)throw new Error("Range: GPU compile expects 2 or 3 arguments (lo, hi, step?)");let i=e[0].re,r=e[1].re,o=e.length===3?e[2].re:1;if(!Number.isFinite(i)||!Number.isFinite(r)||!Number.isFinite(o))throw new Error("Range: GPU compile requires constant numeric bounds (non-constant ranges must be materialized at JS host then uploaded as a uniform)");if(o===0)throw new Error("Range: step cannot be zero");let s=Math.max(0,Math.floor((r-i)/o)+1);if(s===0)throw new Error("Range: empty range (lo > hi for positive step, or lo < hi for negative step)");if(s>256)throw new Error(`Range: GPU compile inlines ranges up to 256 elements (got ${s})`);let a=[];for(let c=0;c<s;c++)a.push(i+c*o);return`${t.language==="wgsl"?`array<f32, ${s}>`:`float[${s}]`}(${a.map(oa).join(", ")})`},Loop:(e,n,t)=>{if(!e[0])throw new Error("Loop: no body");if(!e[1])throw new Error("Loop: no indexing set");let i=e[1];if(!m(i,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let r=i.ops[0],o=i.ops[1];if(!w(r))throw new Error("Loop: index must be a symbol");if(!m(o,"Range"))throw new Error("Loop: expected Range(lo, hi)");let s=r.symbol;OS(s,t.language);let a=Math.floor(o.ops[0].re),u=Math.floor(o.ops[1].re);if(!Number.isFinite(a)||!Number.isFinite(u))throw new Error("Loop: bounds must be finite numbers");let l=t.language==="wgsl",c=l?"i32":"int",f=l?`f32(${s})`:`float(${s})`,p=D.compile(e[0],{...t,var:g=>g===s?f:t.var(g)});return`for (${l?`var ${s}: ${c}`:`${c} ${s}`} = ${a}; ${s} <= ${u}; ${s}++) {
|
|
144
|
+
${r}`:r:n.preamble,s=new TS(i,o),a={target:"javascript",success:!0,code:i,calling:"expression",run:s};return t?wS(a):a}var $Y=100;function oO(e){e.operator;let n=e,t=w(n.op1)?n.op1.symbol:"_",i=n.op2,r=n.op3,o=i.re,s=r.re;return{index:t,lowerExpr:i,upperExpr:r,lowerNum:!isNaN(o)&&Number.isFinite(o)?Math.floor(o):void 0,upperNum:!isNaN(s)&&Number.isFinite(s)?Math.floor(s):void 0}}function Y6(e,n,t){return n!==void 0?String(n):`Math.floor(${D.compile(e,t)})`}function W6(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1]){if(go(n[0]))return nO(e,n[0],i,!1);if(tO(n[0]))return nO(e,n[0],i,!0);throw new Error(`${e}: no indexing set`)}return sO(e,n[0],n.slice(1),i)}function ve(e,n,t,i){if(!n||!go(n))throw new Error(`${e}: ${i!==void 0?`operand ${i}`:"operand"} is not an indexed collection (list/vector/range). Fail closed (D6).`);return t(n)}function Q6(e){if(w(e))switch(e.symbol){case"Add":return"(_a, _b) => _a + _b";case"Multiply":return"(_a, _b) => _a * _b";case"Min":return"(_a, _b) => Math.min(_a, _b)";case"Max":return"(_a, _b) => Math.max(_a, _b)"}}function K6(e,n,t){let i=!1;if(m(e,"Function"))i=e.nops-1===2;else if(w(e)){let r=D.userFunctionLiteral(e.engine,e.symbol);r!==void 0?i=r.nops-1===2:i=t.operators?.(e.symbol)!==void 0}if(i)return`((_f) => (_a, _b) => _f(_a, _b))(${n(e)})`}function du(e,n){let t=De(n.type.type);if(!(t!==void 0&&(t==="number"||$(t,"real")||$(t,"boolean")||$(t,"string"))&&!D.isComplexValued(n)))throw new Error(`${e}: cannot compile \u2014 the interpreter compares elements structurally, but only real/boolean/string elements compare by value on the JavaScript target. Fail closed (D6).`)}function X6(e,n,t){let i=e==="Max"?"Math.max":"Math.min",r=e==="Max"?"-Infinity":"Infinity";return n.length===1&&n[0]&&go(n[0])?`(${t(n[0])}).reduce((_a, _b) => ${i}(_a, _b), ${r})`:n.some(o=>o&&go(o))?`[${n.map(s=>go(s)?`...(${t(s)})`:t(s)).join(", ")}].reduce((_a, _b) => ${i}(_a, _b), ${r})`:`${i}(${n.map(o=>t(o)).join(", ")})`}function eO(e,n,t){let i=e==="GCD"?"_SYS.gcd":"_SYS.lcm",r=e==="GCD"?"0":"1",o=n.map(s=>{if(go(s))return`...(${t(s)})`;if(s.isCollection||s.type.matches("collection"))throw new Error(`${e}: cannot compile \u2014 operand is a collection but not an indexed collection (list/vector/range). Fail closed (D6).`);return t(s)});return`((_a) => _a.length ? _a.reduce((_x, _y) => ${i}(_x, _y)) : ${r})([${o.join(", ")}])`}function nO(e,n,t,i){let r=D.compile(n,t);return i?`((_c) => Array.isArray(_c) ? _c.reduce((_a, _b) => ${e==="Sum"?"_SYS.add":"_SYS.mul"}(_a, _b), ${e==="Sum"?"0":"1"}) : _c)(${r})`:`(${r}).reduce((_a, _b) => _a ${e==="Sum"?"+":"*"} _b, ${e==="Sum"?"0":"1"})`}function sO(e,n,t,i){D.assertScalarBigOpBody(e,n);let{index:r,lowerExpr:o,upperExpr:s,lowerNum:a,upperNum:u}=oO(t[0]),l=t.slice(1),c=e==="Sum",f=c?"+":"*",p=c?"0":"1",d=D.isComplexValued(n),g=I=>l.length>0?sO(e,n,l,I):D.compile(n,I),h=a!==void 0&&u!==void 0;if(h&&a>u)return p;if(h&&u-a+1<=$Y){let T=[];for(let O=a;O<=u;O++){let J={...i,var:G=>G===r?String(O):i.var(G),boundVars:D.withBoundNames(i,[r])};T.push(`(${g(J)})`)}if(!d)return`(${T.join(` ${f} `)})`;let k=T.map((O,J)=>`_t${J}`),A=T.map((O,J)=>`const ${k[J]} = ${O}`).join("; ");if(c){let O=k.map(G=>`${G}.re`).join(" + "),J=k.map(G=>`${G}.im`).join(" + ");return`(() => { ${A}; return { re: ${O}, im: ${J} }; })()`}let P=k[0],B=[A];for(let O=1;O<k.length;O++){let J=P;P=`_p${O}`,B.push(`const ${P} = { re: ${J}.re * ${k[O]}.re - ${J}.im * ${k[O]}.im, im: ${J}.re * ${k[O]}.im + ${J}.im * ${k[O]}.re }`)}return`(() => { ${B.join("; ")}; return ${P}; })()`}let b=Y6(o,a,i),y=Y6(s,u,i),x=g({...i,var:I=>I===r?r:i.var(I),boundVars:D.withBoundNames(i,[r])}),E=D.tempVar(),v=i.iterationBudget,_=I=>v!==void 0?`if (!(_upper - ${r} < ${v})) return ${I}; `:"";if(d){let I=D.tempVar(),T=_("{ re: NaN, im: NaN }");return c?`(() => { let ${E} = { re: 0, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${T}while (${r} <= _upper) { const ${I} = ${x}; ${E} = { re: ${E}.re + ${I}.re, im: ${E}.im + ${I}.im }; ${r}++; } return ${E}; })()`:`(() => { let ${E} = { re: 1, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${T}while (${r} <= _upper) { const ${I} = ${x}; ${E} = { re: ${E}.re * ${I}.re - ${E}.im * ${I}.im, im: ${E}.re * ${I}.im + ${E}.im * ${I}.re }; ${r}++; } return ${E}; })()`}return`(() => { let ${E} = ${p}; let ${r} = ${b}; const _upper = ${y}; ${_("NaN")}while (${r} <= _upper) { ${E} ${f}= ${x}; ${r}++; } return ${E}; })()`}function qY(e,n){let t=n.varsKeys;if(!t||t.size===0)return!1;for(let i of t)if(e.some(r=>r.has(i)))return!0;return!1}function VY(e,n,t){if(!qY(e,t))try{let p=e[0].engine._fn("Integrate",[...e]).evaluate();if(!p.has("Integrate")&&p.isValid&&p.isNaN!==!0)return`(${n(p)})`}catch{}let{index:i,lowerExpr:r,upperExpr:o}=oO(e[1]),s=i,a=e[0];if(m(e[0],"Function")){let p=cn(e[0].ops[1]);p&&(s=p),a=e[0].ops[0]}let u=D.compile(a,{...t,var:p=>p===s?p:t.var(p),boundVars:D.withBoundNames(t,[s])}),l=D.compile(r,t),c=D.compile(o,t);return`${t.quadrature==="monte-carlo"?"_SYS.integrateMC":"_SYS.integrate"}((${s}) => (${u}), ${l}, ${c})`}function JY(e){let n=e.toString();return n.includes("=>")?!1:n.startsWith("function ")&&n.includes(e.name)}function MS(e){if(!Number.isInteger(e))return NaN;if(e<0)return e%2===0?-MS(-e):MS(-e);if(e<=1)return e;let n=0,t=1;for(let i=2;i<=e;i++){let r=n+t;n=t,t=r}return t}var aO={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],Divide:["/",13],Equal:["==",8],NotEqual:["!=",8],LessEqual:["<=",9],GreaterEqual:[">=",9],Less:["<",9],Greater:[">",9],And:["&&",4],Or:["||",3],Not:["!",14]},jY=new Set(["attribute","const","uniform","varying","buffer","shared","coherent","volatile","restrict","readonly","writeonly","layout","centroid","flat","smooth","noperspective","patch","sample","in","out","inout","precision","invariant","precise","subroutine","break","continue","do","for","while","switch","case","default","if","else","discard","return","void","bool","int","uint","float","double","vec2","vec3","vec4","dvec2","dvec3","dvec4","bvec2","bvec3","bvec4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","sampler2D","sampler3D","samplerCube","sampler2DArray","sampler2DShadow","samplerCubeShadow","isampler2D","usampler2D","atomic_uint","image2D","true","false","filter","texture","asm","union","enum","typedef","template","this","packed","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sizeof","cast","namespace","using"]),zY=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","bool","f16","f32","i32","u32","vec2","vec3","vec4","vec2f","vec3f","vec4f","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","array","atomic","ptr","sampler","sampler_comparison","texture_1d","texture_2d","texture_2d_array","texture_3d","texture_cube","texture_cube_array","texture_multisampled_2d","function","private","workgroup","uniform","storage","read","write","read_write","texture","sample","filter","as","async","attribute","auto","binding","cast","compile","do","enum","extern","external","inline","instance","interface","match","namespace","new","null","of","operator","public","reference","self","set","shared","static","super","template","this","typedef","union","unless","using","virtual","where"]);function GY(e){return e==="wgsl"?zY:e==="glsl"?jY:new Set}function OS(e,n){if(GY(n).has(e))throw new Error(`"${e}" is a reserved word in ${n??"this shader language"} and cannot be used as a variable name. Rename it before compiling to a GPU target (fail closed, D6).`);return e}function Hi(e){return e?.language==="wgsl"?"vec2f":"vec2"}function bc(e){return e?.language==="wgsl"?"vec3f":"vec3"}function DS(e){return e?.language==="wgsl"?"bitcast<f32>(0x7fc00000u)":"_gpu_nan()"}function cO(e){if(e===null)return;if(m(e,"Tuple")||m(e,"List")){let t=e.nops;return t>=2&&t<=4?t:void 0}if(D.isComplexValued(e))return 2;let n=e.type.type;if(typeof n!="string"){if(n.kind==="tuple"){let t=n.elements.length;return t>=2&&t<=4?t:void 0}if(n.kind==="list"&&n.dimensions?.length===1){let t=n.dimensions[0];return t>=2&&t<=4?t:void 0}}}function kS(e,n){let t=cO(e);return t===void 0?DS(n):`${n?.language==="wgsl"?`vec${t}f`:`vec${t}`}(${DS(n)})`}function bd(e,n,t,i){return i?.language==="wgsl"?`select(${t}, ${n}, ${e})`:`((${e}) ? (${n}) : (${t}))`}function zb(e,n,t){if(n.length===0)throw new Error(`${e}: needs at least one argument`);if(n.length===1)return t(n[0]);let i=`${e}(${t(n[0])}, ${t(n[1])})`;for(let r=2;r<n.length;r++)i=`${e}(${i}, ${t(n[r])})`;return i}function AS(e,n,t){let i=e.type.type;if(!(typeof i!="string"&&i.kind==="tuple")&&e.type.matches("indexed_collection"))throw new Error(`Point${n.toUpperCase()}: a list of points has no GPU lowering (a point must be a single vec2/vec3/vec4). Fail closed.`);return`${t(e)}.${n}`}function RS(e){return q(e)?e.string?.toLowerCase()??null:null}function uO(e,n,t){let i=Qe(e);return i!==void 0&&Number.isInteger(i)?i.toString():`${t?.language==="wgsl"?"i32":"int"}(${n(e)})`}var UY=100,ZY=4;function lO(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(D.assertScalarBigOpBody(e,n[0]),D.isComplexValued(n[0]))throw new Error(`${e}: complex-valued body not supported in GPU targets`);if(n.length>2)throw new Error(`${e}: multi-index (${n.length-1} indexing sets) is not supported in GPU targets`);let r=n[1];if(!m(r,"Limits"))throw new Error(`${e}: expected Limits indexing set`);let o=r.ops,s=w(o[0])?o[0].symbol:"_",a=o[1].re,u=o[2].re,l=!isNaN(a)&&Number.isFinite(a)?Math.floor(a):void 0,c=!isNaN(u)&&Number.isFinite(u)?Math.floor(u):void 0,f=e==="Sum",p=f?"+":"*",d=f?"0.0":"1.0",g=i.language==="wgsl",h=l!==void 0&&c!==void 0;if(h&&l>c)return d;if(h&&c-l+1<=UY){let P=[];for(let B=l;B<=c;B++){let O=oa(B),J={...i,var:G=>G===s?O:i.var(G),boundVars:D.withBoundNames(i,[s])};P.push(`(${D.compile(n[0],J)})`)}return`(${P.join(` ${p} `)})`}let b=D.tempVar(),y=g?"f32":"float",x=g?"i32":"int",E={...i,var:P=>P===s?g?`f32(${s})`:`float(${s})`:i.var(P),boundVars:D.withBoundNames(i,[s])},v=D.compile(n[0],E),_=l!==void 0?String(l):D.compile(o[1],i),I=c!==void 0?String(c):D.compile(o[2],i);OS(s,i.language);let T=g?`var ${b}: ${y}`:`${y} ${b}`,k=g?`var ${s}: ${x}`:`${x} ${s}`;return[`${T} = ${d};`,`for (${k} = ${_}; ${s} <= ${I}; ${s}++) {`,` ${b} ${p}= ${v};`,"}",`return ${b};`].join(`
|
|
145
|
+
`)}var HY={Add:(e,n,t)=>{if(e.length===0)return"0.0";if(e.length===1)return n(e[0]);if(!e.some(l=>D.isComplexValued(l)))return ra(e.map(l=>n(l)),"0.0","+");let r=e.map(l=>Z6(l,n));if(r.some(l=>l===null)){let l=Hi(t);return e.map(c=>{let f=n(c);return D.isComplexValued(c)?f:`${l}(${f}, 0.0)`}).join(" + ")}let o=[],s=[];for(let l of r)l.re!==null&&o.push(l.re),l.im!==null&&s.push(l.im);let a=ra(o,"0.0","+"),u=ra(s,"0.0","+");return`${Hi(t)}(${a}, ${u})`},Multiply:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);if(!e.some(l=>D.isComplexValued(l)))return ra(e.map(l=>n(l)),"1.0","*");let r=e.findIndex(l=>w(l,"ImaginaryUnit")||N(l)&&l.re===0&&l.im!==0);if(r>=0){let l=e[r],c=w(l,"ImaginaryUnit")?1:l.im,f=e.filter((h,b)=>b!==r),p=Hi(t);if(f.length===0)return`${p}(0.0, ${Jn(c)})`;let d=f.map(h=>qb(h,n(h)));c!==1&&d.unshift(Jn(c));let g=ra(d,"1.0","*");return`${p}(0.0, ${g})`}let o=[],s=[];for(let l of e)D.isComplexValued(l)?s.push(n(l)):o.push(qb(l,n(l)));let a=ra(o,"1.0","*"),u=s[0];for(let l=1;l<s.length;l++)u=`_gpu_cmul(${u}, ${s[l]})`;return a!=="1.0"&&(u=`(${a} * ${u})`),u},Divide:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);let i=D.isComplexValued(e[0]),r=e.length>=2&&D.isComplexValued(e[1]);if(!i&&!r){if(e.length===2){let a=Qe(e[0]),u=Qe(e[1]);return a!==void 0&&u!==void 0&&u!==0?Jn(a/u):u===1?n(e[0]):`${n(e[0])} / ${n(e[1])}`}let s=n(e[0]);for(let a=1;a<e.length;a++)s=`${s} / ${n(e[a])}`;return s}return i&&r?`_gpu_cdiv(${n(e[0])}, ${n(e[1])})`:i&&!r?`(${n(e[0])} / ${n(e[1])})`:`_gpu_cdiv(${Hi(t)}(${n(e[0])}, 0.0), ${n(e[1])})`},Negate:([e],n,t)=>{if(e===null)throw new Error("Negate: no argument");let i=Qe(e);return i!==void 0?Jn(-i):N(e)&&e.im!==0?`${Hi(t)}(${Jn(-e.re)}, ${Jn(-e.im)})`:w(e,"ImaginaryUnit")?`${Hi(t)}(0.0, -1.0)`:`(-${n(e)})`},Abs:(e,n)=>D.isComplexValued(e[0])?`length(${n(e[0])})`:D.isNonNegative(e[0])?n(e[0]):`abs(${n(e[0])})`,Arccos:(e,n)=>D.isComplexValued(e[0])?`_gpu_cacos(${n(e[0])})`:`acos(${n(e[0])})`,Arcsin:(e,n)=>D.isComplexValued(e[0])?`_gpu_casin(${n(e[0])})`:`asin(${n(e[0])})`,Arctan:(e,n)=>D.isComplexValued(e[0])?`_gpu_catan(${n(e[0])})`:`atan(${n(e[0])})`,Ceil:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`ceil(${n(e[0])})`,Clamp:"clamp",Cos:(e,n)=>D.isComplexValued(e[0])?`_gpu_ccos(${n(e[0])})`:`cos(${n(e[0])})`,Degrees:"radians",Exp:(e,n)=>D.isComplexValued(e[0])?`_gpu_cexp(${n(e[0])})`:`exp(${n(e[0])})`,Exp2:"exp2",First:(e,n)=>`${n(e[0])}.x`,Second:(e,n)=>`${n(e[0])}.y`,Third:(e,n)=>`${n(e[0])}.z`,PointX:(e,n)=>AS(e[0],"x",n),PointY:(e,n)=>AS(e[0],"y",n),PointZ:(e,n)=>AS(e[0],"z",n),Floor:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`floor(${n(e[0])})`,Fract:"fract",Ln:(e,n)=>D.isComplexValued(e[0])?`_gpu_cln(${n(e[0])})`:`log(${n(e[0])})`,Log2:"log2",Max:(e,n)=>zb("max",e,n),Min:(e,n)=>zb("min",e,n),ElementMax:(e,n)=>zb("max",e,n),ElementMin:(e,n)=>zb("min",e,n),Mix:"mix",If:(e,n,t)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return bd(n(e[0]),n(e[1]),n(e[2]),t)},When:(e,n,t)=>{if(e.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");return w(e[1],"True")?`(${n(e[0])})`:w(e[1],"False")?kS(e[0],t):bd(n(e[1]),n(e[0]),kS(e[0],t),t)},Which:(e,n,t)=>{if(e.length<2||e.length%2!==0)throw new Error("Which: expected condition/value pairs");let i=e.filter((o,s)=>s%2===1).find(o=>cO(o))??null,r=o=>{if(o>=e.length)return kS(i,t);let s=e[o],a=e[o+1];return w(s,"True")?`(${n(a)})`:bd(n(s),n(a),r(o+2),t)};return r(0)},Match:(e,n,t)=>D.compileMatchTernary(e[0].engine,e,t,{ternary:(i,r,o)=>bd(i,r,o,t),eq:"==",noMatch:DS(t),allowStrings:!1}),Power:(e,n,t)=>{let i=e[0],r=e[1];if(i===null)throw new Error("Power: no argument");if(D.isComplexValued(i)||D.isComplexValued(r)){if(w(i,"ExponentialE"))return`_gpu_cexp(${n(r)})`;let a=Hi(t),u=D.isComplexValued(i)?n(i):`${a}(${n(i)}, 0.0)`,l=D.isComplexValued(r)?n(r):`${a}(${n(r)}, 0.0)`;return`_gpu_cpow(${u}, ${l})`}let o=Qe(i),s=Qe(r);if(o!==void 0&&s!==void 0)return Jn(Math.pow(o,s));if(s===0)return"1.0";if(s===1)return n(i);if(s===.5)return`sqrt(${n(i)})`;if(s!==void 0&&Number.isInteger(s)){let a=s,u=Math.abs(a),l;if(u===1)l=`(${n(i)})`;else if((w(i)||N(i))&&u<=ZY){let c=n(i);l=`(${Array(u).fill(c).join(" * ")})`}else l=`_gpu_powi(${n(i)}, ${oa(u)})`;return a<0?`(1.0 / ${l})`:l}return`pow(${n(i)}, ${n(r)})`},Radians:"radians",Round:(e,n)=>{if(D.isIntegerValued(e[0]))return n(e[0]);let t=n(e[0]);return`(sign(${t}) * floor(abs(${t}) + 0.5))`},Sign:"sign",Sin:(e,n)=>D.isComplexValued(e[0])?`_gpu_csin(${n(e[0])})`:`sin(${n(e[0])})`,Smoothstep:"smoothstep",Sqrt:(e,n)=>{if(D.isComplexValued(e[0]))return`_gpu_csqrt(${n(e[0])})`;let t=Qe(e[0]);return t!==void 0?Jn(Math.sqrt(t)):`sqrt(${n(e[0])})`},Step:"step",Tan:(e,n)=>D.isComplexValued(e[0])?`_gpu_ctan(${n(e[0])})`:`tan(${n(e[0])})`,Truncate:(e,n)=>D.isIntegerValued(e[0])?n(e[0]):`trunc(${n(e[0])})`,Real:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).x`:n(e[0]),Imaginary:(e,n)=>D.isComplexValued(e[0])?`(${n(e[0])}).y`:"0.0",Argument:(e,n,t)=>{if(D.isComplexValued(e[0])){let i=n(e[0]);return`atan(${i}.y, ${i}.x)`}return bd(`${n(e[0])} >= 0.0`,"0.0","3.14159265359",t)},Conjugate:(e,n,t)=>{if(D.isComplexValued(e[0])){let i=Hi(t),r=n(e[0]);return`${i}(${r}.x, -${r}.y)`}return n(e[0])},Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");return`(${t(e)} - ${t(n)} * round(${t(e)} / ${t(n)}))`},Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");if(D.isComplexValued(e))return`_gpu_cdiv(_gpu_ccos(${n(e)}), _gpu_csin(${n(e)}))`;let t=n(e);return`(cos(${t}) / sin(${t}))`},Csc:([e],n,t)=>{if(e===null)throw new Error("Csc: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_csin(${n(e)}))`:`(1.0 / sin(${n(e)}))`},Sec:([e],n,t)=>{if(e===null)throw new Error("Sec: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_ccos(${n(e)}))`:`(1.0 / cos(${n(e)}))`},Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return`(1.5707963267948966 - atan(${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return`asin(1.0 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return`acos(1.0 / (${n(e)}))`},Sinh:(e,n)=>D.isComplexValued(e[0])?`_gpu_csinh(${n(e[0])})`:`sinh(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`_gpu_ccosh(${n(e[0])})`:`cosh(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`_gpu_ctanh(${n(e[0])})`:`tanh(${n(e[0])})`,Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");if(D.isComplexValued(e))return`_gpu_cdiv(_gpu_ccosh(${n(e)}), _gpu_csinh(${n(e)}))`;let t=n(e);return`(cosh(${t}) / sinh(${t}))`},Csch:([e],n,t)=>{if(e===null)throw new Error("Csch: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_csinh(${n(e)}))`:`(1.0 / sinh(${n(e)}))`},Sech:([e],n,t)=>{if(e===null)throw new Error("Sech: no argument");return D.isComplexValued(e)?`_gpu_cdiv(${Hi(t)}(1.0, 0.0), _gpu_ccosh(${n(e)}))`:`(1.0 / cosh(${n(e)}))`},Arcosh:(e,n)=>D.isComplexValued(e[0])?`_gpu_cacosh(${n(e[0])})`:`acosh(${n(e[0])})`,Arsinh:(e,n)=>D.isComplexValued(e[0])?`_gpu_casinh(${n(e[0])})`:`asinh(${n(e[0])})`,Artanh:(e,n)=>D.isComplexValued(e[0])?`_gpu_catanh(${n(e[0])})`:`atanh(${n(e[0])})`,Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return`atanh(1.0 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return`asinh(1.0 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return`acosh(1.0 / (${n(e)}))`},Arctan2:(e,n)=>{if(e.length<2)throw new Error("Arctan2: need two arguments");return`atan(${n(e[0])}, ${n(e[1])})`},Hypot:([e,n],t)=>{if(e===null||n===null)throw new Error("Hypot: need two arguments");return`length(vec2(${t(e)}, ${t(n)}))`},Haversine:([e],n)=>{if(e===null)throw new Error("Haversine: no argument");return`((1.0 - cos(${n(e)})) * 0.5)`},InverseHaversine:([e],n)=>{if(e===null)throw new Error("InverseHaversine: no argument");return`(2.0 * asin(sqrt(${n(e)})))`},Gamma:([e],n)=>{if(e===null)throw new Error("Gamma: no argument");return`_gpu_gamma(${n(e)})`},GammaLn:([e],n)=>{if(e===null)throw new Error("GammaLn: no argument");return`_gpu_gammaln(${n(e)})`},Factorial:([e],n)=>{if(e===null)throw new Error("Factorial: no argument");return`_gpu_gamma(${n(e)} + 1.0)`},Beta:([e,n],t)=>{if(e===null||n===null)throw new Error("Beta: need two arguments");let i=t(e),r=t(n);return`(_gpu_gamma(${i}) * _gpu_gamma(${r}) / _gpu_gamma(${i} + ${r}))`},Erf:([e],n)=>{if(e===null)throw new Error("Erf: no argument");return`_gpu_erf(${n(e)})`},Erfc:([e],n)=>{if(e===null)throw new Error("Erfc: no argument");return`(1.0 - _gpu_erf(${n(e)}))`},ErfInv:([e],n)=>{if(e===null)throw new Error("ErfInv: no argument");return`_gpu_erfinv(${n(e)})`},Heaviside:([e],n)=>{if(e===null)throw new Error("Heaviside: no argument");return`_gpu_heaviside(${n(e)})`},Sinc:([e],n)=>{if(e===null)throw new Error("Sinc: no argument");return`_gpu_sinc(${n(e)})`},FresnelC:([e],n)=>{if(e===null)throw new Error("FresnelC: no argument");return`_gpu_fresnelC(${n(e)})`},FresnelS:([e],n)=>{if(e===null)throw new Error("FresnelS: no argument");return`_gpu_fresnelS(${n(e)})`},BesselJ:([e,n],t,i)=>{if(e===null||n===null)throw new Error("BesselJ: need two arguments");return`_gpu_besselJ(${i?.language==="wgsl"?"i32":"int"}(${t(e)}), ${t(n)})`},Lb:"log2",Log:(e,n)=>{if(e.length===0)throw new Error("Log: no argument");return e.length===1?`(log(${n(e[0])}) / log(10.0))`:`(log(${n(e[0])}) / log(${n(e[1])}))`},Log10:([e],n)=>{if(e===null)throw new Error("Log10: no argument");return`(log(${n(e)}) * 0.4342944819032518)`},Lg:([e],n)=>{if(e===null)throw new Error("Lg: no argument");return`(log(${n(e)}) * 0.4342944819032518)`},Square:([e],n)=>{if(e===null)throw new Error("Square: no argument");if(w(e)||N(e)){let t=n(e);return`(${t} * ${t})`}return`_gpu_powi(${n(e)}, 2.0)`},Root:([e,n],t)=>{if(e===null)throw new Error("Root: no argument");if(n==null)return`sqrt(${t(e)})`;let i=Qe(n);if(i===2)return`sqrt(${t(e)})`;let r=Qe(e);if(r!==void 0&&i!==void 0){let o=Math.pow(r,1/i);return Number.isNaN(o)&&Number.isInteger(i)&&i%2!==0&&r<0?Jn(-Math.pow(-r,1/i)):Jn(o)}if(i!==void 0&&Number.isInteger(i)&&i%2!==0){let o=t(e);return`(sign(${o}) * pow(abs(${o}), ${Jn(1/i)}))`}return`pow(${t(e)}, 1.0 / ${t(n)})`},ColorMix:(e,n)=>{if(e.length<2)throw new Error("ColorMix: need two colors");let t=n(e[0]),i=n(e[1]),r=e.length>=3?n(e[2]):"0.5";return`_gpu_color_mix(${t}, ${i}, ${r})`},ColorContrast:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorContrast: need two colors");return`_gpu_apca(${t(e)}, ${t(n)})`},ContrastingColor:(e,n,t)=>{if(e.length===0)throw new Error("ContrastingColor: no argument");let i=n(e[0]);if(e.length>=3){let u=n(e[1]),l=n(e[2]);return`(abs(_gpu_apca(${i}, ${u})) >= abs(_gpu_apca(${i}, ${l})) ? ${u} : ${l})`}let o=t?.language==="wgsl"?"vec3f":"vec3",s=`${o}(0.0)`,a=`${o}(1.0, 0.0, 0.0)`;return`((_gpu_apca(${i}, ${s}) > 50.0) ? ${s} : ${a})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");let i=RS(n);if(i===null)throw new Error("ColorToColorspace: space must be a string literal");let r=t(e);switch(i){case"oklch":return r;case"oklab":case"lab":return`_gpu_oklch_to_oklab(${r})`;case"rgb":return`_gpu_oklch_to_srgb(${r})`;case"hsl":return`_gpu_rgb_to_hsl(_gpu_oklch_to_srgb(${r}))`;case"hsv":return`_gpu_rgb_to_hsv(_gpu_oklch_to_srgb(${r}))`;default:throw new Error(`ColorToColorspace: unsupported space "${i}" on GPU target`)}},ColorFromColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorFromColorspace: need components and space");let i=RS(n);if(i===null)throw new Error("ColorFromColorspace: space must be a string literal");let r=t(e);switch(i){case"oklch":return r;case"oklab":case"lab":return`_gpu_oklab_to_oklch(${r})`;case"rgb":return`_gpu_srgb_to_oklch(${r})`;case"hsl":return`_gpu_srgb_to_oklch(_gpu_hsl_to_rgb(${r}))`;case"hsv":return`_gpu_srgb_to_oklch(_gpu_hsv_to_rgb(${r}))`;default:throw new Error(`ColorFromColorspace: unsupported space "${i}" on GPU target`)}},Color:([e],n,t)=>{if(e===null)throw new Error("Color: no argument");let i=RS(e);if(i===null)throw new Error("Color: argument must be a string literal on GPU target");let r=Pt(i);if(r===0&&i.trim().toLowerCase()!=="transparent")throw new Error(`Color: invalid color string "${i}"`);let o=r>>>24&255,s=r>>>16&255,a=r>>>8&255,u=Pn({r:o,g:s,b:a});return`${bc(t)}(${Jn(u.L)}, ${Jn(u.C)}, ${Jn(u.H)})`},Rgb:(e,n,t)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_gpu_srgb_to_oklch(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])}))`},Hsv:(e,n,t)=>{if(e.length<3)throw new Error("Hsv: need 3 components");return`_gpu_srgb_to_oklch(_gpu_hsv_to_rgb(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})))`},Hsl:(e,n,t)=>{if(e.length<3)throw new Error("Hsl: need 3 components");return`_gpu_srgb_to_oklch(_gpu_hsl_to_rgb(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})))`},Oklab:(e,n,t)=>{if(e.length<3)throw new Error("Oklab: need 3 components");return`_gpu_oklab_to_oklch(${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])}))`},Oklch:(e,n,t)=>{if(e.length<3)throw new Error("Oklch: need 3 components");return`${bc(t)}(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`},AsOklch:([e],n)=>{if(e===null)throw new Error("AsOklch: no argument");return n(e)},AsOklab:([e],n)=>{if(e===null)throw new Error("AsOklab: no argument");return`_gpu_oklch_to_oklab(${n(e)})`},AsRgb:([e],n)=>{if(e===null)throw new Error("AsRgb: no argument");return`_gpu_oklch_to_srgb(${n(e)})`},AsHsv:([e],n)=>{if(e===null)throw new Error("AsHsv: no argument");return`_gpu_rgb_to_hsv(_gpu_oklch_to_srgb(${n(e)}))`},AsHsl:([e],n)=>{if(e===null)throw new Error("AsHsl: no argument");return`_gpu_rgb_to_hsl(_gpu_oklch_to_srgb(${n(e)}))`},Mandelbrot:([e,n],t,i)=>{if(e===null||n===null)throw new Error("Mandelbrot: missing arguments");let r=uO(n,t,i);return`_fractal_mandelbrot(${t(e)}, ${r})`},Julia:([e,n,t],i,r)=>{if(e===null||n===null||t===null)throw new Error("Julia: missing arguments");let o=uO(t,i,r);return`_fractal_julia(${i(e)}, ${i(n)}, ${o})`},Cross:"cross",Distance:"distance",Dot:"dot",Norm:"length",Length:(e,n,t)=>{throw new Error(`Length (collection element count) is not supported on the ${t.language??"GPU"} target: the '${t.language??"GPU"}' 'length()' builtin is the Euclidean norm (CE 'Norm'), not a count. Fail closed (D6).`)},Normalize:"normalize",Reflect:"reflect",Refract:"refract",Sum:(e,n,t)=>lO("Sum",e,n,t),Product:(e,n,t)=>lO("Product",e,n,t),Range:(e,n,t)=>{if(e.length<2||e.length>3)throw new Error("Range: GPU compile expects 2 or 3 arguments (lo, hi, step?)");let i=e[0].re,r=e[1].re,o=e.length===3?e[2].re:1;if(!Number.isFinite(i)||!Number.isFinite(r)||!Number.isFinite(o))throw new Error("Range: GPU compile requires constant numeric bounds (non-constant ranges must be materialized at JS host then uploaded as a uniform)");if(o===0)throw new Error("Range: step cannot be zero");let s=Math.max(0,Math.floor((r-i)/o)+1);if(s===0)throw new Error("Range: empty range (lo > hi for positive step, or lo < hi for negative step)");if(s>256)throw new Error(`Range: GPU compile inlines ranges up to 256 elements (got ${s})`);let a=[];for(let c=0;c<s;c++)a.push(i+c*o);return`${t.language==="wgsl"?`array<f32, ${s}>`:`float[${s}]`}(${a.map(oa).join(", ")})`},Loop:(e,n,t)=>{if(!e[0])throw new Error("Loop: no body");if(!e[1])throw new Error("Loop: no indexing set");let i=e[1];if(!m(i,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let r=i.ops[0],o=i.ops[1];if(!w(r))throw new Error("Loop: index must be a symbol");if(!m(o,"Range"))throw new Error("Loop: expected Range(lo, hi)");let s=r.symbol;OS(s,t.language);let a=Math.floor(o.ops[0].re),u=Math.floor(o.ops[1].re);if(!Number.isFinite(a)||!Number.isFinite(u))throw new Error("Loop: bounds must be finite numbers");let l=t.language==="wgsl",c=l?"i32":"int",f=l?`f32(${s})`:`float(${s})`,p=D.compile(e[0],{...t,var:g=>g===s?f:t.var(g),boundVars:D.withBoundNames(t,[s])});return`for (${l?`var ${s}: ${c}`:`${c} ${s}`} = ${a}; ${s} <= ${u}; ${s}++) {
|
|
146
146
|
${p};
|
|
147
147
|
}`},GCD:(e,n)=>{if(e.length<2)throw new Error("GCD: need at least two arguments");if(e.length>2)throw new Error("GCD: GPU target supports only two-argument GCD");let t=e[0],i=e[1];if(t===null||i===null)throw new Error("GCD: missing argument");return`_gpu_gcd(${n(t)}, ${n(i)})`},Variance:(e,n)=>{let t;if(e.length===1&&m(e[0],"List"))t=e[0].ops;else if(e.length>=2)t=e;else throw new Error("Variance: GPU target requires a List argument or at least 2 scalar arguments");let i=t.length;if(i<2)throw new Error("Variance: need at least 2 elements");let r=t.map(u=>n(u)),s=`((${r.join(" + ")}) / ${oa(i)})`;return`((${r.map(u=>`(${u} - ${s}) * (${u} - ${s})`).join(" + ")}) / ${oa(i-1)})`},Median:(e,n)=>{let t;if(e.length===1&&m(e[0],"List"))t=e[0].ops;else if(e.length>=1)t=e;else throw new Error("Median: GPU target requires a List argument or at least 1 scalar argument");let i=t.length;if(i===0)throw new Error("Median: empty list");if(i>8)throw new Error(`Median: GPU target supports up to 8 elements via inline sorting network (got ${i}). For larger lists, compute on the CPU and pass the result as a uniform.`);let r=t.map(o=>n(o));return i===1?r[0]:`_gpu_median_${i}(${r.join(", ")})`},Random:(e,n,t)=>{if(e.length===0){if(t.language==="wgsl")throw new Error("Random(): WGSL compile requires an explicit seed argument. WGSL has no gl_FragCoord built-in outside fragment entry points, so the no-arg fallback used in GLSL is unavailable. Use Random(seed) where seed is a deterministic per-invocation value.");return"_gpu_random(gl_FragCoord.x + gl_FragCoord.y * 1024.0)"}if(e.length===1){let i=e[0];if(D.isIntegerValued(i)){let r=n(i);return`floor(_gpu_random(float(${r})) * float(${r}))`}return`_gpu_random(${n(i)})`}if(e.length===2){if(t.language==="wgsl")throw new Error("Random(m, n): WGSL compile requires explicit seeding. Use a seeded variant or compute the integer range manually.");let i=n(e[0]),r=n(e[1]);return`(float(${i}) + floor(_gpu_random(gl_FragCoord.x + gl_FragCoord.y * 1024.0) * float((${r}) - (${i}))))`}throw new Error("Random: GPU compile expects 0, 1, or 2 arguments")},Function:()=>{throw new Error("Anonymous functions (Function) are not supported in GPU targets")}};function Gb(e,n,t,i,r){let o=e[0];if(!m(o))return n(o);let s=o.ops;if(s.length===0)return n(o);let a=s.length,u=s[0],l=m(u)?u.nops:0;if(l===1&&s.every(c=>m(c)&&c.nops===1)){let c=s.map(f=>n(m(f)?f.ops[0]:f));return a>=2&&a<=4?`${t(a)}(${c.join(", ")})`:`${r(a)}(${c.join(", ")})`}if(a===l&&a>=2&&a<=4&&s.every(c=>m(c)&&c.nops===l)){let c=[];for(let f=0;f<l;f++){let p=s.map(d=>n(m(d)?d.ops[f]:d));c.push(`${t(a)}(${p.join(", ")})`)}return`${i(a)}(${c.join(", ")})`}return n(o)}var YY=`
|
|
148
148
|
float _gpu_gamma(float z) {
|
|
@@ -1505,13 +1505,13 @@ ${c}fn main(${g})${h} {
|
|
|
1505
1505
|
`);for(let b of a){let y=this.compileToSource(b.expression);u+=` ${b.variable} = ${y};
|
|
1506
1506
|
`}return p&&(u+=` return output;
|
|
1507
1507
|
`),u+=`}
|
|
1508
|
-
`,u}};var dO={Pi:"np.pi",ExponentialE:"np.e",ImaginaryUnit:"1j",Infinity:"np.inf",NaN:"np.nan",GoldenRatio:"((1 + np.sqrt(5)) / 2)",CatalanConstant:"0.915965594177219015054603514932384110774",EulerGamma:"0.5772156649015328606065120900824024310421"};function mO(e,n,t){if(n.length<2)throw new Error(`${e}: expected at least two arguments`);let i=n[0]?.engine?.tolerance??1e-10,r=e==="Equal"?"<=":">",o=(a,u)=>`(abs((${t(a)}) - (${t(u)})) ${r} ${i})`;if(n.length===2)return o(n[0],n[1]);let s=[];for(let a=0;a<n.length-1;a++)s.push(o(n[a],n[a+1]));return`(${s.join(" and ")})`}function EO(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)):D.compile(e,n)}function vO(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)+1):`${D.compile(e,n)} + 1`}function gO(e,n,t){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);D.assertScalarBigOpBody(e,n[0]);let i=n[0],r=n.slice(1),o=[],s=t;for(let l of r){if(!m(l,"Limits"))throw new Error(`${e}: expected a Limits indexing set`);let c=l.ops,f=c[0];if(!w(f))throw new Error(`${e}: index must be a symbol`);let p=f.symbol,d=c[1],g=c[2];if(d===void 0||g===void 0||w(g,"Nothing")||g.isInfinity||d.isInfinity)throw new Error(`${e}: an unbounded range is not supported`);let h=EO(d,s),b=vO(g,s);o.push(`for ${p} in range(${h}, ${b})`);let y=s;s={...y,var:x=>x===p?p:y.var(x)}}let u=`${D.compile(i,s)} ${o.join(" ")}`;return e==="Sum"?`sum(${u})`:`math.prod(${u})`}function LS(e){return(e.trim()===""?"pass":e).split(`
|
|
1508
|
+
`,u}};var dO={Pi:"np.pi",ExponentialE:"np.e",ImaginaryUnit:"1j",Infinity:"np.inf",NaN:"np.nan",GoldenRatio:"((1 + np.sqrt(5)) / 2)",CatalanConstant:"0.915965594177219015054603514932384110774",EulerGamma:"0.5772156649015328606065120900824024310421"};function mO(e,n,t){if(n.length<2)throw new Error(`${e}: expected at least two arguments`);let i=n[0]?.engine?.tolerance??1e-10,r=e==="Equal"?"<=":">",o=(a,u)=>`(abs((${t(a)}) - (${t(u)})) ${r} ${i})`;if(n.length===2)return o(n[0],n[1]);let s=[];for(let a=0;a<n.length-1;a++)s.push(o(n[a],n[a+1]));return`(${s.join(" and ")})`}function EO(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)):D.compile(e,n)}function vO(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)+1):`${D.compile(e,n)} + 1`}function gO(e,n,t){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);D.assertScalarBigOpBody(e,n[0]);let i=n[0],r=n.slice(1),o=[],s=t;for(let l of r){if(!m(l,"Limits"))throw new Error(`${e}: expected a Limits indexing set`);let c=l.ops,f=c[0];if(!w(f))throw new Error(`${e}: index must be a symbol`);let p=f.symbol,d=c[1],g=c[2];if(d===void 0||g===void 0||w(g,"Nothing")||g.isInfinity||d.isInfinity)throw new Error(`${e}: an unbounded range is not supported`);let h=EO(d,s),b=vO(g,s);o.push(`for ${p} in range(${h}, ${b})`);let y=s;s={...y,var:x=>x===p?p:y.var(x),boundVars:D.withBoundNames(y,[p])}}let u=`${D.compile(i,s)} ${o.join(" ")}`;return e==="Sum"?`sum(${u})`:`math.prod(${u})`}function LS(e){return(e.trim()===""?"pass":e).split(`
|
|
1509
1509
|
`).map(t=>` ${t}`).join(`
|
|
1510
1510
|
`)}function Ub(e,n){if(w(e,"Nothing"))return"";if(!m(e))return D.compile(e,n);let t=e.operator;if(t==="Break")return"break";if(t==="Continue")return"continue";if(t==="Return")return`return ${D.compile(e.ops[0],n)}`;if(t==="If"){let r=`if ${D.compile(e.ops[0],n)}:
|
|
1511
1511
|
${LS(Ub(e.ops[1],n))}`;return e.ops.length>2&&(r+=`
|
|
1512
1512
|
else:
|
|
1513
1513
|
${LS(Ub(e.ops[2],n))}`),r}return t==="Block"?e.ops.map(i=>Ub(i,n)).filter(i=>i!=="").join(`
|
|
1514
|
-
`):t==="Loop"?SO(e.ops,n):D.compile(e,n)}function SO(e,n){if(!e[0])throw new Error("Loop: no body");let t=e[0],i=e.slice(1),r,o=n;if(i.length===0)r="while True:";else{if(i.length>1)throw new Error("Loop: multiple Element clauses are not supported by the Python target");let a=i[0];if(!m(a,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let u=a.ops[0],l=a.ops[1];if(!w(u))throw new Error("Loop: index must be a symbol");if(!m(l,"Range")||l.ops.length>2)throw new Error("Loop: only a single ascending step-1 Range(lo, hi) is supported by the Python target");let c=u.symbol,f=EO(l.ops[0],n),p=vO(l.ops[1],n);r=`for ${c} in range(${f}, ${p}):`;let d=n;o={...d,var:g=>g===c?c:d.var(g)}}let s=LS(Ub(t,o));return`${r}
|
|
1514
|
+
`):t==="Loop"?SO(e.ops,n):D.compile(e,n)}function SO(e,n){if(!e[0])throw new Error("Loop: no body");let t=e[0],i=e.slice(1),r,o=n;if(i.length===0)r="while True:";else{if(i.length>1)throw new Error("Loop: multiple Element clauses are not supported by the Python target");let a=i[0];if(!m(a,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let u=a.ops[0],l=a.ops[1];if(!w(u))throw new Error("Loop: index must be a symbol");if(!m(l,"Range")||l.ops.length>2)throw new Error("Loop: only a single ascending step-1 Range(lo, hi) is supported by the Python target");let c=u.symbol,f=EO(l.ops[0],n),p=vO(l.ops[1],n);r=`for ${c} in range(${f}, ${p}):`;let d=n;o={...d,var:g=>g===c?c:d.var(g),boundVars:D.withBoundNames(d,[c])}}let s=LS(Ub(t,o));return`${r}
|
|
1515
1515
|
${s}`}var hO={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],Divide:["/",13],Power:["**",15],LessEqual:["<=",9],GreaterEqual:[">=",9],Less:["<",9],Greater:[">",9],And:["and",4],Or:["or",3],Not:["not",14]};function Zb(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}var _O=`def _ce_bcast(_op, *args):
|
|
1516
1516
|
_arrs = [np.asarray(a) for a in args]
|
|
1517
1517
|
_lens = [a.shape[0] for a in _arrs if a.ndim > 0]
|
|
@@ -1545,7 +1545,7 @@ ${s}`}var hO={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],D
|
|
|
1545
1545
|
return _a
|
|
1546
1546
|
`;function bO(e){let n=e;return n.includes("_ce_rref(")&&(n=`${NO}
|
|
1547
1547
|
${n}`),n.includes("_ce_bcast(")&&(n=`${_O}
|
|
1548
|
-
${n}`),n}function yO(e,n,t,i){let r=t.map(s=>Zb(s)?`${e}(${i(s)})`:i(s));if(r.length===0)return e==="np.max"?"-np.inf":"np.inf";let o=r[0];for(let s=1;s<r.length;s++)o=`${n}(${o}, ${r[s]})`;return o}function Fe(e,n,t,i){if(!n||!(n.type.matches("list")||n.type.matches("indexed_collection")))throw new Error(`${e}: ${i!==void 0?`operand ${i}`:"operand"} is not an indexed collection (list/vector/range). Fail closed (D6).`);return t(n)}function Wt(e,n,t){if(n&&m(n,"Function"))return t(n);if(n&&w(n)){let i={Add:"+",Subtract:"-",Multiply:"*",Divide:"/"}[n.symbol];if(i!==void 0)return`(lambda _a, _b: _a ${i} _b)`}throw new Error(`${e}: the function operand does not compile on the Python target (only function literals and binary arithmetic operator symbols lower to a Python lambda). Fail closed (D6).`)}var xO={Add:(e,n)=>e.length===0?"0":e.length===1?n(e[0]):e.map(t=>n(t)).join(" + "),Multiply:(e,n)=>e.length===0?"1":e.length===1?n(e[0]):e.map(t=>n(t)).join(" * "),Divide:(e,n)=>{if(e.length===0)return"1";if(e.length===1)return n(e[0]);if(e.length===2)return`${n(e[0])} / ${n(e[1])}`;let t=n(e[0]);for(let i=1;i<e.length;i++)t=`${t} / ${n(e[i])}`;return t},Sin:(e,n)=>D.isComplexValued(e[0])?`cmath.sin(${n(e[0])})`:`np.sin(${n(e[0])})`,Cos:(e,n)=>D.isComplexValued(e[0])?`cmath.cos(${n(e[0])})`:`np.cos(${n(e[0])})`,Tan:(e,n)=>D.isComplexValued(e[0])?`cmath.tan(${n(e[0])})`:`np.tan(${n(e[0])})`,Arcsin:(e,n)=>D.isComplexValued(e[0])?`cmath.asin(${n(e[0])})`:`np.arcsin(${n(e[0])})`,Arccos:(e,n)=>D.isComplexValued(e[0])?`cmath.acos(${n(e[0])})`:`np.arccos(${n(e[0])})`,Arctan:(e,n)=>D.isComplexValued(e[0])?`cmath.atan(${n(e[0])})`:`np.arctan(${n(e[0])})`,Arctan2:"np.arctan2",Sinh:(e,n)=>D.isComplexValued(e[0])?`cmath.sinh(${n(e[0])})`:`np.sinh(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`cmath.cosh(${n(e[0])})`:`np.cosh(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`cmath.tanh(${n(e[0])})`:`np.tanh(${n(e[0])})`,Arsinh:"np.arcsinh",Arcosh:"np.arccosh",Artanh:"np.arctanh",Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");return`(np.cos(${n(e)}) / np.sin(${n(e)}))`},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return`(1 / np.sin(${n(e)}))`},Sec:([e],n)=>{if(e===null)throw new Error("Sec: no argument");return`(1 / np.cos(${n(e)}))`},Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return`(np.pi / 2 - np.arctan(${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return`np.arcsin(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return`np.arccos(1 / (${n(e)}))`},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return`(np.cosh(${n(e)}) / np.sinh(${n(e)}))`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return`(1 / np.sinh(${n(e)}))`},Sech:([e],n)=>{if(e===null)throw new Error("Sech: no argument");return`(1 / np.cosh(${n(e)}))`},Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return`np.arctanh(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return`np.arcsinh(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return`np.arccosh(1 / (${n(e)}))`},Lb:"np.log2",Square:([e],n)=>{if(e===null)throw new Error("Square: no argument");return`np.square(${n(e)})`},Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return`np.modf(${n(e)})[0]`},Exp:(e,n)=>D.isComplexValued(e[0])?`cmath.exp(${n(e[0])})`:`np.exp(${n(e[0])})`,Ln:(e,n)=>D.isComplexValued(e[0])?`cmath.log(${n(e[0])})`:`np.log(${n(e[0])})`,Log:(e,n)=>e.length===1?`np.log10(${n(e[0])})`:e.length===2?`(np.log(${n(e[0])}) / np.log(${n(e[1])}))`:"np.log10",Log10:"np.log10",Log2:"np.log2",Exp2:"np.exp2",Power:(e,n)=>e.length!==2?"np.power":D.isComplexValued(e[0])||D.isComplexValued(e[1])?`(${n(e[0])} ** ${n(e[1])})`:`np.power(${n(e[0])}, ${n(e[1])})`,Sqrt:(e,n)=>D.isComplexValued(e[0])?`cmath.sqrt(${n(e[0])})`:`np.sqrt(${n(e[0])})`,Root:(e,n)=>{if(e.length!==2)return"np.power";let[t,i]=e,r=Qe(i);if(r!==void 0&&Number.isInteger(r)&&r%2!==0){let o=n(t);return`(np.sign(${o}) * np.power(np.abs(${o}), 1.0 / ${n(i)}))`}return`np.power(${n(t)}, 1.0 / ${n(i)})`},Abs:(e,n)=>D.isComplexValued(e[0])?`abs(${n(e[0])})`:`np.abs(${n(e[0])})`,Sign:"np.sign",Floor:"np.floor",Ceil:"np.ceil",Round:([e],n)=>{if(e===null)throw new Error("Round: no argument");let t=n(e);return`(np.sign(${t}) * np.floor(np.abs(${t}) + 0.5))`},Truncate:"np.trunc",Min:(e,n)=>yO("np.min","np.minimum",e,n),Max:(e,n)=>yO("np.max","np.maximum",e,n),ElementMax:(e,n)=>{if(!e.some(Zb)){let t=n(e[0]);for(let i=1;i<e.length;i++)t=`np.maximum(${t}, ${n(e[i])})`;return t}return`_ce_bcast('max', ${e.map(t=>n(t)).join(", ")})`},ElementMin:(e,n)=>{if(!e.some(Zb)){let t=n(e[0]);for(let i=1;i<e.length;i++)t=`np.minimum(${t}, ${n(e[i])})`;return t}return`_ce_bcast('min', ${e.map(t=>n(t)).join(", ")})`},Clamp:(e,n)=>e.some(Zb)?`_ce_bcast('clip', ${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`np.clip(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`,Mod:"np.mod",Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");let i=t(e),r=t(n);return`(${i} - ${r} * np.round(${i} / ${r}))`},Real:"np.real",Imaginary:"np.imag",Argument:"np.angle",Conjugate:"np.conj",Sum:(e,n,t)=>gO("Sum",e,t),Product:(e,n,t)=>gO("Product",e,t),Mean:"np.mean",Median:"np.median",Variance:"np.var",StandardDeviation:"np.std",Covariance:([e,n],t)=>{if(e===null||n===null)throw new Error("Covariance: expected two collection arguments");return`np.cov(${t(e)}, ${t(n)})[0][1]`},PopulationCovariance:([e,n],t)=>{if(e===null||n===null)throw new Error("PopulationCovariance: expected two collection arguments");return`np.cov(${t(e)}, ${t(n)}, ddof=0)[0][1]`},Correlation:([e,n],t)=>{if(e===null||n===null)throw new Error("Correlation: expected two collection arguments");return`np.corrcoef(${t(e)}, ${t(n)})[0][1]`},Dot:"np.dot",Cross:"np.cross",Norm:"np.linalg.norm",Determinant:"np.linalg.det",Inverse:"np.linalg.inv",Transpose:"np.transpose",MatrixMultiply:"np.matmul",ConjugateTranspose:(e,n)=>`np.transpose(np.conjugate(${n(e[0])}))`,Diagonal:"np.diag",MatrixPower:"np.linalg.matrix_power",Rank:"np.ndim",RowReduce:(e,n)=>`_ce_rref(${n(e[0])})`,Equal:(e,n)=>mO("Equal",e,n),NotEqual:(e,n)=>mO("NotEqual",e,n),Less:"np.less",LessEqual:"np.less_equal",Greater:"np.greater",GreaterEqual:"np.greater_equal",And:"np.logical_and",Or:"np.logical_or",Not:"np.logical_not",If:(e,n)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return`((${n(e[1])}) if (${n(e[0])}) else (${n(e[2])}))`},When:(e,n)=>{if(e.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");return w(e[1],"True")?`(${n(e[0])})`:w(e[1],"False")?"float('nan')":`((${n(e[0])}) if (${n(e[1])}) else float('nan'))`},Which:(e,n)=>{if(e.length<2||e.length%2!==0)throw new Error("Which: expected condition/value pairs");let t=i=>{if(i>=e.length)return"float('nan')";let r=e[i],o=e[i+1];return w(r,"True")?`(${n(o)})`:`((${n(o)}) if (${n(r)}) else ${t(i+2)})`};return t(0)},Match:()=>{throw new Error("Match: pattern matching is not supported by the Python compile target in v1. Fail closed (D6).")},Loop:(e,n,t)=>SO(e,t),Erf:"scipy.special.erf",Erfc:"scipy.special.erfc",Gamma:"scipy.special.gamma",GammaLn:"scipy.special.loggamma",Factorial:"scipy.special.factorial",GammaRegularized:"scipy.special.gammaincc",BetaRegularized:([e,n,t],i)=>{if(e===null||n===null||t===null)throw new Error("BetaRegularized: missing argument");return`scipy.special.betainc(${i(n)}, ${i(t)}, ${i(e)})`},List:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Matrix:(e,n)=>`np.array(${n(e[0])})`,Tuple:(e,n)=>`(${e.map(t=>n(t)).join(", ")})`,Sequence:(e,n)=>`np.array([${e.map(t=>n(t)).join(", ")}])`,Range:(e,n)=>{if(e.length===0)return"[]";let t=e.length===1?"1":n(e[0]),i=e.length===1?n(e[0]):n(e[1]);return e.length<=2?`(lambda _a, _b: [float(_a + (1 if _b >= _a else -1) * _i) for _i in range(int(np.floor(abs(_b - _a))) + 1)])(${t}, ${i})`:`(lambda _a, _b, _s: [] if _s == 0 else [float(_a + _s * _i) for _i in range(max(0, int(np.floor((_b - _a) / _s)) + 1))])(${t}, ${i}, ${n(e[2])})`},Function:(e,n,t)=>{if(e[0]==null)throw new Error("Function: missing body");let i=e[0];for(;m(i,"Block")&&i.nops===1;)i=i.ops[0];if(m(i,"Block"))throw new Error("Function: a multi-statement (Block) body cannot compile to a Python lambda. Fail closed (D6).");let r=e.slice(1).map(s=>cn(s)||"_"),o=D.compile(i.canonical,{...t,var:s=>r.includes(s)?s:t.var(s)});return`(lambda ${r.join(", ")}: ${o})`},Length:(e,n)=>`len(${Fe("Length",e[0],n)})`,Count:(e,n)=>`len(${Fe("Count",e[0],n)})`,IsEmpty:(e,n)=>`(len(${Fe("IsEmpty",e[0],n)}) == 0)`,At:(e,n)=>{let t=Fe("At",e[0],n);if(e[1]==null||e.length!==2)throw new Error("At: only the single-index form compiles. Fail closed (D6).");return`(lambda _l, _i: _l[int(_i) - 1] if 1 <= _i <= len(_l) else (_l[int(_i)] if -len(_l) <= _i <= -1 else float('nan')))(${t}, ${n(e[1])})`},First:(e,n)=>`(lambda _l: _l[0] if len(_l) > 0 else float('nan'))(${Fe("First",e[0],n)})`,Second:(e,n)=>`(lambda _l: _l[1] if len(_l) > 1 else float('nan'))(${Fe("Second",e[0],n)})`,Third:(e,n)=>`(lambda _l: _l[2] if len(_l) > 2 else float('nan'))(${Fe("Third",e[0],n)})`,Last:(e,n)=>`(lambda _l: _l[-1] if len(_l) > 0 else float('nan'))(${Fe("Last",e[0],n)})`,Rest:(e,n)=>`${Fe("Rest",e[0],n)}[1:]`,Most:(e,n)=>`${Fe("Most",e[0],n)}[:-1]`,Take:(e,n)=>{let t=Fe("Take",e[0],n);if(e[1]==null)throw new Error("Take: missing count");return`${t}[:max(0, int(${n(e[1])}))]`},Drop:(e,n)=>{let t=Fe("Drop",e[0],n);if(e[1]==null)throw new Error("Drop: missing count");return`${t}[max(0, int(${n(e[1])})):]`},Reverse:(e,n)=>`${Fe("Reverse",e[0],n)}[::-1]`,Sort:(e,n)=>{if(e.length>1)throw new Error("Sort: a custom comparator does not compile; only the default ascending numeric sort is supported. Fail closed (D6).");return`sorted(${Fe("Sort",e[0],n)})`},Ordering:(e,n)=>{if(e.length>1)throw new Error("Ordering: a custom ordering function does not compile. Fail closed (D6).");return`(lambda _l: [_i + 1 for _i in sorted(range(len(_l)), key=lambda _j: _l[_j])])(${Fe("Ordering",e[0],n)})`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`*${Fe("Join",t,n,i+1)}`).join(", ")}]`,Append:(e,n)=>{let t=Fe("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[*${t}, ${n(e[1])}]`},IndexOf:(e,n)=>{let t=Fe("IndexOf",e[0],n);if(e[1]==null)throw new Error("IndexOf: missing value");return`(lambda _l, _v: _l.index(_v) + 1 if _v in _l else 0)(${t}, ${n(e[1])})`},Contains:(e,n)=>{e[0]&&du("Contains",e[0]);let t=Fe("Contains",e[0],n);if(e[1]==null)throw new Error("Contains: missing value");return`(${n(e[1])} in ${t})`},Unique:(e,n)=>(e[0]&&du("Unique",e[0]),`list(dict.fromkeys(${Fe("Unique",e[0],n)}))`),Zip:(e,n)=>e.length===0?"[]":`[list(_t) for _t in zip(${e.map((i,r)=>Fe("Zip",i,n,r+1)).join(", ")})]`,Linspace:(e,n)=>{if(e[0]==null)throw new Error("Linspace: missing argument");let t=e[1]==null?"1":n(e[0]),i=e[1]==null?n(e[0]):n(e[1]),r=e[2]==null?"50":n(e[2]);return`[float(_v) for _v in np.linspace(${t}, ${i}, max(0, int(${r})))]`},Map:(e,n)=>{let t=Fe("Map",e[0],n);if(e.length>2)throw new Error("Map: multi-collection form is not compiled");if(e[1]==null)throw new Error("Map: missing mapping function");return`(lambda _f: [_f(_x) for _x in ${t}])(${Wt("Map",e[1],n)})`},Filter:(e,n)=>{let t=Fe("Filter",e[0],n);if(e[1]==null)throw new Error("Filter: missing predicate");return`(lambda _f: [_x for _x in ${t} if _f(_x)])(${Wt("Filter",e[1],n)})`},CountIf:(e,n)=>{let t=Fe("CountIf",e[0],n);if(e[1]==null)throw new Error("CountIf: missing predicate");return`(lambda _f: sum(1 for _x in ${t} if _f(_x)))(${Wt("CountIf",e[1],n)})`},Find:(e,n)=>{let t=Fe("Find",e[0],n);if(e[1]==null)throw new Error("Find: missing predicate");return`(lambda _f: next((_x for _x in ${t} if _f(_x)), float('nan')))(${Wt("Find",e[1],n)})`},IndexWhere:(e,n)=>{let t=Fe("IndexWhere",e[0],n);if(e[1]==null)throw new Error("IndexWhere: missing predicate");return`(lambda _f: next((_i + 1 for _i, _x in enumerate(${t}) if _f(_x)), 0))(${Wt("IndexWhere",e[1],n)})`},Position:(e,n)=>{let t=Fe("Position",e[0],n);if(e[1]==null)throw new Error("Position: missing predicate");return`(lambda _f: [_i + 1 for _i, _x in enumerate(${t}) if _f(_x)])(${Wt("Position",e[1],n)})`},Any:(e,n)=>{let t=Fe("Any",e[0],n);if(e[1]==null)throw new Error("Any: only the predicate form compiles. Fail closed (D6).");return`(lambda _f: any(_f(_x) for _x in ${t}))(${Wt("Any",e[1],n)})`},All:(e,n)=>{let t=Fe("All",e[0],n);if(e[1]==null)throw new Error("All: only the predicate form compiles. Fail closed (D6).");return`(lambda _f: all(_f(_x) for _x in ${t}))(${Wt("All",e[1],n)})`},TakeWhile:(e,n)=>{let t=Fe("TakeWhile",e[0],n);if(e[1]==null)throw new Error("TakeWhile: missing predicate");return`(lambda _f, _l: _l[:next((_i for _i, _x in enumerate(_l) if not _f(_x)), len(_l))])(${Wt("TakeWhile",e[1],n)}, ${t})`},DropWhile:(e,n)=>{let t=Fe("DropWhile",e[0],n);if(e[1]==null)throw new Error("DropWhile: missing predicate");return`(lambda _f, _l: _l[next((_i for _i, _x in enumerate(_l) if not _f(_x)), len(_l)):])(${Wt("DropWhile",e[1],n)}, ${t})`},FlatMap:(e,n)=>{let t=Fe("FlatMap",e[0],n);if(e[1]==null)throw new Error("FlatMap: missing mapping function");return`(lambda _f, _l: [_y for _x in _l for _y in (lambda _r: _r if isinstance(_r, list) else [_r])(_f(_x))])(${Wt("FlatMap",e[1],n)}, ${t})`},Reduce:(e,n)=>{let t=Fe("Reduce",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Reduce: missing combiner");let o=w(i)?{Add:"sum(_l)",Multiply:'__import__("math").prod(_l)',Min:"min(_l)",Max:"max(_l)"}[i.symbol]:void 0;if(o!==void 0)return r!=null?`(lambda _l: ${{"sum(_l)":`sum(_l, ${n(r)})`,'__import__("math").prod(_l)':`__import__("math").prod(_l, start=${n(r)})`,"min(_l)":`min([${n(r)}, *_l])`,"max(_l)":`max([${n(r)}, *_l])`}[o]})(${t})`:`(lambda _l: float('nan') if len(_l) == 0 else ${o})(${t})`;if(m(i,"Function")&&i.nops-1===2||w(i)){if(r==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");return`__import__('functools').reduce(${Wt("Reduce",i,n)}, ${t}, ${n(r)})`}throw new Error("Reduce: the combiner does not compile to a function on the Python target. Fail closed (D6).")},Scan:(e,n)=>{let t=Fe("Scan",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Scan: missing combiner");let s=(w(i)?{Add:"(lambda _a, _b: _a + _b)",Multiply:"(lambda _a, _b: _a * _b)",Min:"(lambda _a, _b: min(_a, _b))",Max:"(lambda _a, _b: max(_a, _b))"}[i.symbol]:void 0)??(m(i,"Function")&&i.nops-1===2||w(i)?Wt("Scan",i,n):void 0);if(s===void 0)throw new Error("Scan: the combiner does not compile to a function on the Python target. Fail closed (D6).");return r!=null?`list(__import__('itertools').accumulate(${t}, ${s}, initial=${n(r)}))[1:]`:`list(__import__('itertools').accumulate(${t}, ${s}))`},Tabulate:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Tabulate: missing argument");if(e.length>3)throw new Error("Tabulate: only the 1-D and 2-D forms compile. Fail closed (D6).");for(let o=1;o<e.length;o++){let s=Qe(e[o]);if(s!==void 0&&Math.round(s)<=0)throw new Error(`Tabulate: a statically non-positive dimension (${s}) is inert in the interpreter. Fail closed (D6).`)}let t=Wt("Tabulate",e[0],n),i=n(e[1]);return e.length===2?`(lambda _f: [_f(_i + 1) for _i in range(max(0, round(${i})))])(${t})`:`(lambda _f: [[_f(_i + 1, _j + 1) for _j in range(max(0, round(${n(e[2])})))] for _i in range(max(0, round(${i})))])(${t})`},Fill:(e,n)=>{let t=e[1];if(e[0]==null||t==null)throw new Error("Fill: missing argument");if(!m(t)||t.ops.length!==2)throw new Error("Fill: only the (function, (rows, cols)) form compiles. Fail closed (D6).");let i=Wt("Fill",e[0],n),r=n(t.ops[0]);return`(lambda _f: [[_f(_i + 1, _j + 1) for _j in range(max(0, round(${n(t.ops[1])})))] for _i in range(max(0, round(${r})))])(${i})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");if(!D.isBooleanValued(e[0]))throw new Error("Boole: the argument is not provably boolean. Fail closed (D6).");return`(1 if ${n(e[0])} else 0)`},KroneckerDelta:(e,n)=>{if(e.length===0||e[0]==null)throw new Error("KroneckerDelta: missing argument");let t=e[0].engine.tolerance??1e-10;return e.length===1?`(1 if abs(${n(e[0])}) <= ${t} else 0)`:`(lambda *_v: 1 if all(abs(_x - _v[0]) <= ${t} for _x in _v) else 0)(${e.map(i=>n(i)).join(", ")})`},Element:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Element: missing argument");return du("Element",e[1]),`(${n(e[0])} in ${Fe("Element",e[1],n)})`},Identity:(e,n)=>{if(e[0]==null)throw new Error("Identity: missing argument");return n(e[0])},Apply:(e,n)=>{if(e[0]==null)throw new Error("Apply: missing function");return`(${n(e[0])})(${e.slice(1).map(t=>n(t)).join(", ")})`},Flatten:(e,n)=>{if(e[1]!=null)throw new Error("Flatten: an explicit depth does not compile on the Python target. Fail closed (D6).");return`(lambda _l: (lambda _f: _f(_f, _l))(lambda _f, _x: [_y for _e in _x for _y in (_f(_f, _e) if isinstance(_e, list) else [_e])]))(${Fe("Flatten",e[0],n)})`},Shape:(e,n)=>{if(e[0]==null)throw new Error("Shape: missing argument");return`list(np.shape(${n(e[0])}))`},Reshape:(e,n)=>{let t=Fe("Reshape",e[0],n),i=e[1];if(i==null)throw new Error("Reshape: missing shape");if(!m(i)||i.ops.length===0||i.ops.length>2)throw new Error("Reshape: only a 1-D or 2-D target shape compiles. Fail closed (D6).");return`np.resize(np.asarray(${t}), (${i.ops.map(r=>n(r)).join(", ")},)).tolist()`},Trace:(e,n)=>{if(e.length>1)throw new Error("Trace: explicit axes do not compile. Fail closed (D6).");return`float(np.trace(np.asarray(${Fe("Trace",e[0],n)})))`}},Ec=class{includeImports;useScipy;constructor(n={}){this.includeImports=n.includeImports??!1,this.useScipy=n.useScipy??!1}getOperators(){return hO}getFunctions(){return xO}createTarget(n={}){return{language:"python",chainOp:"and",bindExpr:(t,i)=>`(lambda ${t.map(r=>r[0]).join(", ")}: ${i})(${t.map(r=>r[1]).join(", ")})`,operators:t=>hO[t],functions:t=>xO[t],var:t=>dO[t],complex:(t,i)=>`complex(${t}, ${i})`,string:t=>JSON.stringify(t),number:t=>isFinite(t)?t.toString():t===1/0?"np.inf":t===-1/0?"-np.inf":"np.nan",indent:0,ws:t=>t??"",preamble:"",bareStatementBlocks:!0,declare:t=>"",block:t=>{if(t.length===0)return"";let i=t.length-1;return/^(for|while)\b/.test(t[i])?t.push("return None"):t[i]=`return ${t[i]}`,t.join(`
|
|
1548
|
+
${n}`),n}function yO(e,n,t,i){let r=t.map(s=>Zb(s)?`${e}(${i(s)})`:i(s));if(r.length===0)return e==="np.max"?"-np.inf":"np.inf";let o=r[0];for(let s=1;s<r.length;s++)o=`${n}(${o}, ${r[s]})`;return o}function Fe(e,n,t,i){if(!n||!(n.type.matches("list")||n.type.matches("indexed_collection")))throw new Error(`${e}: ${i!==void 0?`operand ${i}`:"operand"} is not an indexed collection (list/vector/range). Fail closed (D6).`);return t(n)}function Wt(e,n,t){if(n&&m(n,"Function"))return t(n);if(n&&w(n)){let i={Add:"+",Subtract:"-",Multiply:"*",Divide:"/"}[n.symbol];if(i!==void 0)return`(lambda _a, _b: _a ${i} _b)`}throw new Error(`${e}: the function operand does not compile on the Python target (only function literals and binary arithmetic operator symbols lower to a Python lambda). Fail closed (D6).`)}var xO={Add:(e,n)=>e.length===0?"0":e.length===1?n(e[0]):e.map(t=>n(t)).join(" + "),Multiply:(e,n)=>e.length===0?"1":e.length===1?n(e[0]):e.map(t=>n(t)).join(" * "),Divide:(e,n)=>{if(e.length===0)return"1";if(e.length===1)return n(e[0]);if(e.length===2)return`${n(e[0])} / ${n(e[1])}`;let t=n(e[0]);for(let i=1;i<e.length;i++)t=`${t} / ${n(e[i])}`;return t},Sin:(e,n)=>D.isComplexValued(e[0])?`cmath.sin(${n(e[0])})`:`np.sin(${n(e[0])})`,Cos:(e,n)=>D.isComplexValued(e[0])?`cmath.cos(${n(e[0])})`:`np.cos(${n(e[0])})`,Tan:(e,n)=>D.isComplexValued(e[0])?`cmath.tan(${n(e[0])})`:`np.tan(${n(e[0])})`,Arcsin:(e,n)=>D.isComplexValued(e[0])?`cmath.asin(${n(e[0])})`:`np.arcsin(${n(e[0])})`,Arccos:(e,n)=>D.isComplexValued(e[0])?`cmath.acos(${n(e[0])})`:`np.arccos(${n(e[0])})`,Arctan:(e,n)=>D.isComplexValued(e[0])?`cmath.atan(${n(e[0])})`:`np.arctan(${n(e[0])})`,Arctan2:"np.arctan2",Sinh:(e,n)=>D.isComplexValued(e[0])?`cmath.sinh(${n(e[0])})`:`np.sinh(${n(e[0])})`,Cosh:(e,n)=>D.isComplexValued(e[0])?`cmath.cosh(${n(e[0])})`:`np.cosh(${n(e[0])})`,Tanh:(e,n)=>D.isComplexValued(e[0])?`cmath.tanh(${n(e[0])})`:`np.tanh(${n(e[0])})`,Arsinh:"np.arcsinh",Arcosh:"np.arccosh",Artanh:"np.arctanh",Cot:([e],n)=>{if(e===null)throw new Error("Cot: no argument");return`(np.cos(${n(e)}) / np.sin(${n(e)}))`},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return`(1 / np.sin(${n(e)}))`},Sec:([e],n)=>{if(e===null)throw new Error("Sec: no argument");return`(1 / np.cos(${n(e)}))`},Arccot:([e],n)=>{if(e===null)throw new Error("Arccot: no argument");return`(np.pi / 2 - np.arctan(${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return`np.arcsin(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return`np.arccos(1 / (${n(e)}))`},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return`(np.cosh(${n(e)}) / np.sinh(${n(e)}))`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return`(1 / np.sinh(${n(e)}))`},Sech:([e],n)=>{if(e===null)throw new Error("Sech: no argument");return`(1 / np.cosh(${n(e)}))`},Arcoth:([e],n)=>{if(e===null)throw new Error("Arcoth: no argument");return`np.arctanh(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return`np.arcsinh(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return`np.arccosh(1 / (${n(e)}))`},Lb:"np.log2",Square:([e],n)=>{if(e===null)throw new Error("Square: no argument");return`np.square(${n(e)})`},Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return`np.modf(${n(e)})[0]`},Exp:(e,n)=>D.isComplexValued(e[0])?`cmath.exp(${n(e[0])})`:`np.exp(${n(e[0])})`,Ln:(e,n)=>D.isComplexValued(e[0])?`cmath.log(${n(e[0])})`:`np.log(${n(e[0])})`,Log:(e,n)=>e.length===1?`np.log10(${n(e[0])})`:e.length===2?`(np.log(${n(e[0])}) / np.log(${n(e[1])}))`:"np.log10",Log10:"np.log10",Log2:"np.log2",Exp2:"np.exp2",Power:(e,n)=>e.length!==2?"np.power":D.isComplexValued(e[0])||D.isComplexValued(e[1])?`(${n(e[0])} ** ${n(e[1])})`:`np.power(${n(e[0])}, ${n(e[1])})`,Sqrt:(e,n)=>D.isComplexValued(e[0])?`cmath.sqrt(${n(e[0])})`:`np.sqrt(${n(e[0])})`,Root:(e,n)=>{if(e.length!==2)return"np.power";let[t,i]=e,r=Qe(i);if(r!==void 0&&Number.isInteger(r)&&r%2!==0){let o=n(t);return`(np.sign(${o}) * np.power(np.abs(${o}), 1.0 / ${n(i)}))`}return`np.power(${n(t)}, 1.0 / ${n(i)})`},Abs:(e,n)=>D.isComplexValued(e[0])?`abs(${n(e[0])})`:`np.abs(${n(e[0])})`,Sign:"np.sign",Floor:"np.floor",Ceil:"np.ceil",Round:([e],n)=>{if(e===null)throw new Error("Round: no argument");let t=n(e);return`(np.sign(${t}) * np.floor(np.abs(${t}) + 0.5))`},Truncate:"np.trunc",Min:(e,n)=>yO("np.min","np.minimum",e,n),Max:(e,n)=>yO("np.max","np.maximum",e,n),ElementMax:(e,n)=>{if(!e.some(Zb)){let t=n(e[0]);for(let i=1;i<e.length;i++)t=`np.maximum(${t}, ${n(e[i])})`;return t}return`_ce_bcast('max', ${e.map(t=>n(t)).join(", ")})`},ElementMin:(e,n)=>{if(!e.some(Zb)){let t=n(e[0]);for(let i=1;i<e.length;i++)t=`np.minimum(${t}, ${n(e[i])})`;return t}return`_ce_bcast('min', ${e.map(t=>n(t)).join(", ")})`},Clamp:(e,n)=>e.some(Zb)?`_ce_bcast('clip', ${n(e[0])}, ${n(e[1])}, ${n(e[2])})`:`np.clip(${n(e[0])}, ${n(e[1])}, ${n(e[2])})`,Mod:"np.mod",Remainder:([e,n],t)=>{if(e===null||n===null)throw new Error("Remainder: missing argument");let i=t(e),r=t(n);return`(${i} - ${r} * np.round(${i} / ${r}))`},Real:"np.real",Imaginary:"np.imag",Argument:"np.angle",Conjugate:"np.conj",Sum:(e,n,t)=>gO("Sum",e,t),Product:(e,n,t)=>gO("Product",e,t),Mean:"np.mean",Median:"np.median",Variance:"np.var",StandardDeviation:"np.std",Covariance:([e,n],t)=>{if(e===null||n===null)throw new Error("Covariance: expected two collection arguments");return`np.cov(${t(e)}, ${t(n)})[0][1]`},PopulationCovariance:([e,n],t)=>{if(e===null||n===null)throw new Error("PopulationCovariance: expected two collection arguments");return`np.cov(${t(e)}, ${t(n)}, ddof=0)[0][1]`},Correlation:([e,n],t)=>{if(e===null||n===null)throw new Error("Correlation: expected two collection arguments");return`np.corrcoef(${t(e)}, ${t(n)})[0][1]`},Dot:"np.dot",Cross:"np.cross",Norm:"np.linalg.norm",Determinant:"np.linalg.det",Inverse:"np.linalg.inv",Transpose:"np.transpose",MatrixMultiply:"np.matmul",ConjugateTranspose:(e,n)=>`np.transpose(np.conjugate(${n(e[0])}))`,Diagonal:"np.diag",MatrixPower:"np.linalg.matrix_power",Rank:"np.ndim",RowReduce:(e,n)=>`_ce_rref(${n(e[0])})`,Equal:(e,n)=>mO("Equal",e,n),NotEqual:(e,n)=>mO("NotEqual",e,n),Less:"np.less",LessEqual:"np.less_equal",Greater:"np.greater",GreaterEqual:"np.greater_equal",And:"np.logical_and",Or:"np.logical_or",Not:"np.logical_not",If:(e,n)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return`((${n(e[1])}) if (${n(e[0])}) else (${n(e[2])}))`},When:(e,n)=>{if(e.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");return w(e[1],"True")?`(${n(e[0])})`:w(e[1],"False")?"float('nan')":`((${n(e[0])}) if (${n(e[1])}) else float('nan'))`},Which:(e,n)=>{if(e.length<2||e.length%2!==0)throw new Error("Which: expected condition/value pairs");let t=i=>{if(i>=e.length)return"float('nan')";let r=e[i],o=e[i+1];return w(r,"True")?`(${n(o)})`:`((${n(o)}) if (${n(r)}) else ${t(i+2)})`};return t(0)},Match:()=>{throw new Error("Match: pattern matching is not supported by the Python compile target in v1. Fail closed (D6).")},Loop:(e,n,t)=>SO(e,t),Erf:"scipy.special.erf",Erfc:"scipy.special.erfc",Gamma:"scipy.special.gamma",GammaLn:"scipy.special.loggamma",Factorial:"scipy.special.factorial",GammaRegularized:"scipy.special.gammaincc",BetaRegularized:([e,n,t],i)=>{if(e===null||n===null||t===null)throw new Error("BetaRegularized: missing argument");return`scipy.special.betainc(${i(n)}, ${i(t)}, ${i(e)})`},List:(e,n)=>`[${e.map(t=>n(t)).join(", ")}]`,Matrix:(e,n)=>`np.array(${n(e[0])})`,Tuple:(e,n)=>`(${e.map(t=>n(t)).join(", ")})`,Sequence:(e,n)=>`np.array([${e.map(t=>n(t)).join(", ")}])`,Range:(e,n)=>{if(e.length===0)return"[]";let t=e.length===1?"1":n(e[0]),i=e.length===1?n(e[0]):n(e[1]);return e.length<=2?`(lambda _a, _b: [float(_a + (1 if _b >= _a else -1) * _i) for _i in range(int(np.floor(abs(_b - _a))) + 1)])(${t}, ${i})`:`(lambda _a, _b, _s: [] if _s == 0 else [float(_a + _s * _i) for _i in range(max(0, int(np.floor((_b - _a) / _s)) + 1))])(${t}, ${i}, ${n(e[2])})`},Function:(e,n,t)=>{if(e[0]==null)throw new Error("Function: missing body");let i=e[0];for(;m(i,"Block")&&i.nops===1;)i=i.ops[0];if(m(i,"Block"))throw new Error("Function: a multi-statement (Block) body cannot compile to a Python lambda. Fail closed (D6).");let r=e.slice(1).map(s=>cn(s)||"_"),o=D.compile(i.canonical,{...t,var:s=>r.includes(s)?s:t.var(s),boundVars:D.withBoundNames(t,r)});return`(lambda ${r.join(", ")}: ${o})`},Length:(e,n)=>`len(${Fe("Length",e[0],n)})`,Count:(e,n)=>`len(${Fe("Count",e[0],n)})`,IsEmpty:(e,n)=>`(len(${Fe("IsEmpty",e[0],n)}) == 0)`,At:(e,n)=>{let t=Fe("At",e[0],n);if(e[1]==null||e.length!==2)throw new Error("At: only the single-index form compiles. Fail closed (D6).");return`(lambda _l, _i: _l[int(_i) - 1] if 1 <= _i <= len(_l) else (_l[int(_i)] if -len(_l) <= _i <= -1 else float('nan')))(${t}, ${n(e[1])})`},First:(e,n)=>`(lambda _l: _l[0] if len(_l) > 0 else float('nan'))(${Fe("First",e[0],n)})`,Second:(e,n)=>`(lambda _l: _l[1] if len(_l) > 1 else float('nan'))(${Fe("Second",e[0],n)})`,Third:(e,n)=>`(lambda _l: _l[2] if len(_l) > 2 else float('nan'))(${Fe("Third",e[0],n)})`,Last:(e,n)=>`(lambda _l: _l[-1] if len(_l) > 0 else float('nan'))(${Fe("Last",e[0],n)})`,Rest:(e,n)=>`${Fe("Rest",e[0],n)}[1:]`,Most:(e,n)=>`${Fe("Most",e[0],n)}[:-1]`,Take:(e,n)=>{let t=Fe("Take",e[0],n);if(e[1]==null)throw new Error("Take: missing count");return`${t}[:max(0, int(${n(e[1])}))]`},Drop:(e,n)=>{let t=Fe("Drop",e[0],n);if(e[1]==null)throw new Error("Drop: missing count");return`${t}[max(0, int(${n(e[1])})):]`},Reverse:(e,n)=>`${Fe("Reverse",e[0],n)}[::-1]`,Sort:(e,n)=>{if(e.length>1)throw new Error("Sort: a custom comparator does not compile; only the default ascending numeric sort is supported. Fail closed (D6).");return`sorted(${Fe("Sort",e[0],n)})`},Ordering:(e,n)=>{if(e.length>1)throw new Error("Ordering: a custom ordering function does not compile. Fail closed (D6).");return`(lambda _l: [_i + 1 for _i in sorted(range(len(_l)), key=lambda _j: _l[_j])])(${Fe("Ordering",e[0],n)})`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`*${Fe("Join",t,n,i+1)}`).join(", ")}]`,Append:(e,n)=>{let t=Fe("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[*${t}, ${n(e[1])}]`},IndexOf:(e,n)=>{let t=Fe("IndexOf",e[0],n);if(e[1]==null)throw new Error("IndexOf: missing value");return`(lambda _l, _v: _l.index(_v) + 1 if _v in _l else 0)(${t}, ${n(e[1])})`},Contains:(e,n)=>{e[0]&&du("Contains",e[0]);let t=Fe("Contains",e[0],n);if(e[1]==null)throw new Error("Contains: missing value");return`(${n(e[1])} in ${t})`},Unique:(e,n)=>(e[0]&&du("Unique",e[0]),`list(dict.fromkeys(${Fe("Unique",e[0],n)}))`),Zip:(e,n)=>e.length===0?"[]":`[list(_t) for _t in zip(${e.map((i,r)=>Fe("Zip",i,n,r+1)).join(", ")})]`,Linspace:(e,n)=>{if(e[0]==null)throw new Error("Linspace: missing argument");let t=e[1]==null?"1":n(e[0]),i=e[1]==null?n(e[0]):n(e[1]),r=e[2]==null?"50":n(e[2]);return`[float(_v) for _v in np.linspace(${t}, ${i}, max(0, int(${r})))]`},Map:(e,n)=>{let t=Fe("Map",e[0],n);if(e.length>2)throw new Error("Map: multi-collection form is not compiled");if(e[1]==null)throw new Error("Map: missing mapping function");return`(lambda _f: [_f(_x) for _x in ${t}])(${Wt("Map",e[1],n)})`},Filter:(e,n)=>{let t=Fe("Filter",e[0],n);if(e[1]==null)throw new Error("Filter: missing predicate");return`(lambda _f: [_x for _x in ${t} if _f(_x)])(${Wt("Filter",e[1],n)})`},CountIf:(e,n)=>{let t=Fe("CountIf",e[0],n);if(e[1]==null)throw new Error("CountIf: missing predicate");return`(lambda _f: sum(1 for _x in ${t} if _f(_x)))(${Wt("CountIf",e[1],n)})`},Find:(e,n)=>{let t=Fe("Find",e[0],n);if(e[1]==null)throw new Error("Find: missing predicate");return`(lambda _f: next((_x for _x in ${t} if _f(_x)), float('nan')))(${Wt("Find",e[1],n)})`},IndexWhere:(e,n)=>{let t=Fe("IndexWhere",e[0],n);if(e[1]==null)throw new Error("IndexWhere: missing predicate");return`(lambda _f: next((_i + 1 for _i, _x in enumerate(${t}) if _f(_x)), 0))(${Wt("IndexWhere",e[1],n)})`},Position:(e,n)=>{let t=Fe("Position",e[0],n);if(e[1]==null)throw new Error("Position: missing predicate");return`(lambda _f: [_i + 1 for _i, _x in enumerate(${t}) if _f(_x)])(${Wt("Position",e[1],n)})`},Any:(e,n)=>{let t=Fe("Any",e[0],n);if(e[1]==null)throw new Error("Any: only the predicate form compiles. Fail closed (D6).");return`(lambda _f: any(_f(_x) for _x in ${t}))(${Wt("Any",e[1],n)})`},All:(e,n)=>{let t=Fe("All",e[0],n);if(e[1]==null)throw new Error("All: only the predicate form compiles. Fail closed (D6).");return`(lambda _f: all(_f(_x) for _x in ${t}))(${Wt("All",e[1],n)})`},TakeWhile:(e,n)=>{let t=Fe("TakeWhile",e[0],n);if(e[1]==null)throw new Error("TakeWhile: missing predicate");return`(lambda _f, _l: _l[:next((_i for _i, _x in enumerate(_l) if not _f(_x)), len(_l))])(${Wt("TakeWhile",e[1],n)}, ${t})`},DropWhile:(e,n)=>{let t=Fe("DropWhile",e[0],n);if(e[1]==null)throw new Error("DropWhile: missing predicate");return`(lambda _f, _l: _l[next((_i for _i, _x in enumerate(_l) if not _f(_x)), len(_l)):])(${Wt("DropWhile",e[1],n)}, ${t})`},FlatMap:(e,n)=>{let t=Fe("FlatMap",e[0],n);if(e[1]==null)throw new Error("FlatMap: missing mapping function");return`(lambda _f, _l: [_y for _x in _l for _y in (lambda _r: _r if isinstance(_r, list) else [_r])(_f(_x))])(${Wt("FlatMap",e[1],n)}, ${t})`},Reduce:(e,n)=>{let t=Fe("Reduce",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Reduce: missing combiner");let o=w(i)?{Add:"sum(_l)",Multiply:'__import__("math").prod(_l)',Min:"min(_l)",Max:"max(_l)"}[i.symbol]:void 0;if(o!==void 0)return r!=null?`(lambda _l: ${{"sum(_l)":`sum(_l, ${n(r)})`,'__import__("math").prod(_l)':`__import__("math").prod(_l, start=${n(r)})`,"min(_l)":`min([${n(r)}, *_l])`,"max(_l)":`max([${n(r)}, *_l])`}[o]})(${t})`:`(lambda _l: float('nan') if len(_l) == 0 else ${o})(${t})`;if(m(i,"Function")&&i.nops-1===2||w(i)){if(r==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");return`__import__('functools').reduce(${Wt("Reduce",i,n)}, ${t}, ${n(r)})`}throw new Error("Reduce: the combiner does not compile to a function on the Python target. Fail closed (D6).")},Scan:(e,n)=>{let t=Fe("Scan",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Scan: missing combiner");let s=(w(i)?{Add:"(lambda _a, _b: _a + _b)",Multiply:"(lambda _a, _b: _a * _b)",Min:"(lambda _a, _b: min(_a, _b))",Max:"(lambda _a, _b: max(_a, _b))"}[i.symbol]:void 0)??(m(i,"Function")&&i.nops-1===2||w(i)?Wt("Scan",i,n):void 0);if(s===void 0)throw new Error("Scan: the combiner does not compile to a function on the Python target. Fail closed (D6).");return r!=null?`list(__import__('itertools').accumulate(${t}, ${s}, initial=${n(r)}))[1:]`:`list(__import__('itertools').accumulate(${t}, ${s}))`},Tabulate:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Tabulate: missing argument");if(e.length>3)throw new Error("Tabulate: only the 1-D and 2-D forms compile. Fail closed (D6).");for(let o=1;o<e.length;o++){let s=Qe(e[o]);if(s!==void 0&&Math.round(s)<=0)throw new Error(`Tabulate: a statically non-positive dimension (${s}) is inert in the interpreter. Fail closed (D6).`)}let t=Wt("Tabulate",e[0],n),i=n(e[1]);return e.length===2?`(lambda _f: [_f(_i + 1) for _i in range(max(0, round(${i})))])(${t})`:`(lambda _f: [[_f(_i + 1, _j + 1) for _j in range(max(0, round(${n(e[2])})))] for _i in range(max(0, round(${i})))])(${t})`},Fill:(e,n)=>{let t=e[1];if(e[0]==null||t==null)throw new Error("Fill: missing argument");if(!m(t)||t.ops.length!==2)throw new Error("Fill: only the (function, (rows, cols)) form compiles. Fail closed (D6).");let i=Wt("Fill",e[0],n),r=n(t.ops[0]);return`(lambda _f: [[_f(_i + 1, _j + 1) for _j in range(max(0, round(${n(t.ops[1])})))] for _i in range(max(0, round(${r})))])(${i})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");if(!D.isBooleanValued(e[0]))throw new Error("Boole: the argument is not provably boolean. Fail closed (D6).");return`(1 if ${n(e[0])} else 0)`},KroneckerDelta:(e,n)=>{if(e.length===0||e[0]==null)throw new Error("KroneckerDelta: missing argument");let t=e[0].engine.tolerance??1e-10;return e.length===1?`(1 if abs(${n(e[0])}) <= ${t} else 0)`:`(lambda *_v: 1 if all(abs(_x - _v[0]) <= ${t} for _x in _v) else 0)(${e.map(i=>n(i)).join(", ")})`},Element:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Element: missing argument");return du("Element",e[1]),`(${n(e[0])} in ${Fe("Element",e[1],n)})`},Identity:(e,n)=>{if(e[0]==null)throw new Error("Identity: missing argument");return n(e[0])},Apply:(e,n)=>{if(e[0]==null)throw new Error("Apply: missing function");return`(${n(e[0])})(${e.slice(1).map(t=>n(t)).join(", ")})`},Flatten:(e,n)=>{if(e[1]!=null)throw new Error("Flatten: an explicit depth does not compile on the Python target. Fail closed (D6).");return`(lambda _l: (lambda _f: _f(_f, _l))(lambda _f, _x: [_y for _e in _x for _y in (_f(_f, _e) if isinstance(_e, list) else [_e])]))(${Fe("Flatten",e[0],n)})`},Shape:(e,n)=>{if(e[0]==null)throw new Error("Shape: missing argument");return`list(np.shape(${n(e[0])}))`},Reshape:(e,n)=>{let t=Fe("Reshape",e[0],n),i=e[1];if(i==null)throw new Error("Reshape: missing shape");if(!m(i)||i.ops.length===0||i.ops.length>2)throw new Error("Reshape: only a 1-D or 2-D target shape compiles. Fail closed (D6).");return`np.resize(np.asarray(${t}), (${i.ops.map(r=>n(r)).join(", ")},)).tolist()`},Trace:(e,n)=>{if(e.length>1)throw new Error("Trace: explicit axes do not compile. Fail closed (D6).");return`float(np.trace(np.asarray(${Fe("Trace",e[0],n)})))`}},Ec=class{includeImports;useScipy;constructor(n={}){this.includeImports=n.includeImports??!1,this.useScipy=n.useScipy??!1}getOperators(){return hO}getFunctions(){return xO}createTarget(n={}){return{language:"python",chainOp:"and",bindExpr:(t,i)=>`(lambda ${t.map(r=>r[0]).join(", ")}: ${i})(${t.map(r=>r[1]).join(", ")})`,operators:t=>hO[t],functions:t=>xO[t],var:t=>dO[t],complex:(t,i)=>`complex(${t}, ${i})`,string:t=>JSON.stringify(t),number:t=>isFinite(t)?t.toString():t===1/0?"np.inf":t===-1/0?"-np.inf":"np.nan",indent:0,ws:t=>t??"",preamble:"",bareStatementBlocks:!0,declare:t=>"",block:t=>{if(t.length===0)return"";let i=t.length-1;return/^(for|while)\b/.test(t[i])?t.push("return None"):t[i]=`return ${t[i]}`,t.join(`
|
|
1549
1549
|
`)},...n}}makeVarResolver(n,t){return i=>{if(t?.includes(i))return i;if(n&&i in n){let r=n[i];return typeof r=="string"?r:JSON.stringify(r)}return dO[i]}}compile(n,t={}){try{return this.compileOrThrow(n,t)}catch(i){if(t.fallback!==!0)throw i;let r=i.message;return console.warn(`Compilation fallback for "${n.operator}" (target: python): ${r}`),D.buildInterpreterFallback(n,r,"python",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=po(n);let i=t.vars,r=this.createTarget({var:this.makeVarResolver(i)}),o=bO(D.compile(n,r));this.includeImports&&(o=this.withImports(o));let s={target:"python",success:!0,code:o};return D.withReferences(s,n,r,i?new Set(Object.keys(i)):void 0)}withImports(n){let t=`import numpy as np
|
|
1550
1550
|
`;return t+=`import cmath
|
|
1551
1551
|
`,this.useScipy&&(t+=`import scipy.special
|
|
@@ -1579,7 +1579,7 @@ ${n}`}compileToSource(n,t={}){let i=t.vars,r=this.createTarget({var:this.makeVar
|
|
|
1579
1579
|
() => ${t(i+2)}
|
|
1580
1580
|
)`};return t(0)},Match:()=>{throw new Error("Match: pattern matching is not supported by the interval-js compile target in v1. Fail closed (D6).")},Equal:(e,n)=>Sc("_IA.equal",e,n),NotEqual:(e,n)=>Sc("_IA.notEqual",e,n),LessEqual:(e,n)=>Sc("_IA.lessEqual",e,n),GreaterEqual:(e,n)=>Sc("_IA.greaterEqual",e,n),Less:(e,n)=>Sc("_IA.less",e,n),Greater:(e,n)=>Sc("_IA.greater",e,n),And:(e,n)=>$O("_IA.and",e,n),Or:(e,n)=>$O("_IA.or",e,n),Not:(e,n)=>`_IA.not(${n(e[0])})`},FW=100;function BW(e){e.operator;let n=e,t=w(n.op1)?n.op1.symbol:"_",i=n.op2,r=n.op3,o=i.re,s=r.re;return{index:t,lowerExpr:i,upperExpr:r,lowerNum:!isNaN(o)&&Number.isFinite(o)?Math.floor(o):void 0,upperNum:!isNaN(s)&&Number.isFinite(s)?Math.floor(s):void 0}}function qO(e,n,t){return n!==void 0?String(n):`Math.floor(((_b) => (_b && _b.value ? _b.value.hi : _b.hi))(${D.compile(e,t)}))`}function VO(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(D.assertScalarBigOpBody(e,n[0]),n.length>2)throw new Error(`${e}: multi-index (${n.length-1} indexing sets) is not supported in the interval target`);let{index:r,lowerExpr:o,upperExpr:s,lowerNum:a,upperNum:u}=BW(n[1]),l=e==="Sum",c=l?"_IA.add":"_IA.mul",f=l?"_IA.point(0)":"_IA.point(1)",p=a!==void 0&&u!==void 0;if(p&&a>u)return f;if(p&&u-a+1<=FW){let x=[];for(let v=a;v<=u;v++){let _={...i,var:I=>I===r?`_IA.point(${v})`:i.var(I),boundVars:D.withBoundNames(i,[r])};x.push(D.compile(n[0],_))}let E=x[x.length-1];for(let v=x.length-2;v>=0;v--)E=`${c}(${x[v]}, ${E})`;return E}let d=qO(o,a,i),g=qO(s,u,i),h=D.tempVar(),b=D.compile(n[0],{...i,var:y=>y===r?`_IA.point(${r})`:i.var(y),boundVars:D.withBoundNames(i,[r])});return`(() => { let ${h} = ${f}; const _upper = ${g}; for (let ${r} = ${d}; ${r} <= _upper; ${r}++) { ${h} = ${c}(${h}, ${b}); } return ${h}; })()`}var sN=class extends Function{IA=BO;constructor(n,t=""){return super("_IA","_",t?`${t};return ${n}`:`return ${n}`),new Proxy(this,{apply:(i,r,o)=>{try{let s=o.map(zO);return super.apply(r,[this.IA,...s])}catch{return{kind:"entire"}}},get:(i,r)=>r==="toString"?()=>n:r==="isCompiled"?!0:Reflect.get(i,r)})}};function aN(e){return e!==null&&typeof e=="object"}function JO(e){return aN(e)&&"lo"in e&&"hi"in e}function $W(e){return typeof e=="number"?{lo:e,hi:e}:{kind:"entire"}}function jO(e){if(JO(e))return(Number(e.lo)+Number(e.hi))/2;if(aN(e)){let n={};for(let[t,i]of Object.entries(e))n[t]=jO(i);return n}return e}function zO(e){if(e==null||JO(e))return e;if(aN(e)){let n={};for(let[t,i]of Object.entries(e))n[t]=zO(i);return n}return typeof e=="number"?{lo:e,hi:e}:e}var _c=class{getOperators(){return LW}getFunctions(){return oN}createTarget(n={}){return{language:"interval-javascript",operators:()=>{},functions:t=>oN[t],var:t=>({Pi:"_IA.point(Math.PI)",ExponentialE:"_IA.point(Math.E)",NaN:"{ lo: NaN, hi: NaN }",ImaginaryUnit:"{ lo: NaN, hi: NaN }",Half:"_IA.point(0.5)",MachineEpsilon:"_IA.point(Number.EPSILON)",GoldenRatio:"_IA.point((1 + Math.sqrt(5)) / 2)",CatalanConstant:"_IA.point(0.91596559417721901)",EulerGamma:"_IA.point(0.57721566490153286)"})[t],string:t=>JSON.stringify(t),number:t=>`_IA.point(${t})`,indent:0,ws:t=>t??"",preamble:"",...n}}compile(n,t={}){let i;try{i=this.compileOrThrow(n,t)}catch(r){if(t.fallback!==!0)throw r;return this.buildIntervalFallback(n,r.message,t)}if(!i.success&&t.fallback===!0){let r=i.error??`Cannot compile \`${n.operator}\` to the interval-js target`;return this.buildIntervalFallback(n,r,t)}return i}buildIntervalFallback(n,t,i){console.warn(`Compilation fallback for "${n.operator}" (target: interval-js): ${t}`);let r=D.buildInterpreterFallback(n,t,"interval-js",this.createTarget(),i.vars?new Set(Object.keys(i.vars)):void 0),o=r.run;return{...r,run:(...a)=>$W(o(...a.map(jO)))}}compileOrThrow(n,t={}){n=po(n);let{functions:i,vars:r,preamble:o}=t,s=n.unknowns,a={},u="";if(i)for(let[f,p]of Object.entries(i))typeof p=="function"?(u+=`const ${f} = ${p.toString()};
|
|
1581
1581
|
`,a[f]=f):typeof p=="string"&&(a[f]=p);let l=this.createTarget({functions:f=>a?.[f]?a[f]:oN[f],var:f=>{if(r&&f in r)return r[f];let p={Pi:"_IA.point(Math.PI)",ExponentialE:"_IA.point(Math.E)",NaN:"{ lo: NaN, hi: NaN }",ImaginaryUnit:"{ lo: NaN, hi: NaN }",Half:"_IA.point(0.5)",MachineEpsilon:"_IA.point(Number.EPSILON)",GoldenRatio:"_IA.point((1 + Math.sqrt(5)) / 2)",CatalanConstant:"_IA.point(0.91596559417721901)",EulerGamma:"_IA.point(0.57721566490153286)"};if(f in p)return p[f];if(s.includes(f))return`_.${f}`;if(n.engine._getSymbolValue(f)===void 0)return`_.${f}`},preamble:(o??"")+u,userFunctions:{defs:new Map,compiling:new Set}}),c=qW(n,l);return D.withReferences(c,n,l,r?new Set(Object.keys(r)):void 0)}};function qW(e,n){let t;try{t=D.compile(e,n)}catch(s){return{target:"interval-js",success:!1,code:"",error:s.message}}let i=D.userFunctionsPreamble(n),r=i?n.preamble?`${n.preamble}
|
|
1582
|
-
${i}`:i:n.preamble,o=new sN(t,r);return{target:"interval-js",success:!0,code:t,calling:"expression",run:o}}var i0=class{_targets=new Map;register(n,t){k4(n),R4(t),this._targets.set(n,t)}get(n){return this._targets.get(n)}list(){return[...this._targets.keys()]}unregister(n){this._targets.delete(n)}registerDefaults(){this.register("javascript",new hc),this.register("glsl",new yc),this.register("wgsl",new yd),this.register("python",new Ec),this.register("interval-js",new _c)}};var r0=class{_listeners=[];_registered=new WeakSet;_pending=!1;_version=0;listen(n){return this._registered.has(n)||(this._registered.add(n),this._listeners.push(n)),()=>this._unsubscribe(n)}_unsubscribe(n){this._registered.has(n)&&(this._registered.delete(n),this._listeners=this._listeners.filter(t=>t!==n))}notify(){if(this._pending)return;this._pending=!0;let n=this._version+1;queueMicrotask(()=>{if(n!==this._version+1){this._pending=!1;return}this.notifyNow()})}notifyNow(){this._version++;for(let n of this._listeners)try{n?.onConfigurationChange?.()}catch(t){console.error("Listener error:",t)}this._pending=!1}};var o0=class{_generation=0;_mutationGeneration=0;_ephemeralWriteDepth=0;_tracker=new r0;get generation(){return this._generation}set generation(n){this._generation=n}get mutationGeneration(){return this._mutationGeneration}set mutationGeneration(n){this._mutationGeneration=n}get ephemeralWriteDepth(){return this._ephemeralWriteDepth}set ephemeralWriteDepth(n){this._ephemeralWriteDepth=n}reset(n){this._generation+=1,this._mutationGeneration+=1,n.refreshNumericConstants(),n.resetCommonSymbols(),n.purgeCaches(),this._tracker.notifyNow()}listen(n){return this._tracker.listen(n)}};function VW(e){return!!(e===void 0||e==="Number"||e===!0||Array.isArray(e)&&e.includes("Number"))}function GO(e,n,t,i){let r=i?.canonical??!0,o=i?.metadata,s=t.normalize(),a=s.toLowerCase();if(a==="infinity"||a==="+infinity")return e.PositiveInfinity;if(a==="-infinity")return e.NegativeInfinity;if(e.strict&&!yn(s))return e.error(["invalid-symbol",vi(s)],s);if(!r)return new hr(e,s,{metadata:o});if(e._isShadowedParameter(s)){let f=e._shadowedParameterType(s);if(f!==void 0){let d=e._shadowedParameterDef(s);if(d!==void 0)return new hr(e,s,{metadata:o,def:d});let g=e.context.lexicalScope;for(;g.noAutoDeclare&&g.parent;)g=g.parent;let h=g.bindings.get(s)??e._declareSymbolValue(s,{type:f,inferred:!1},g);return e._setShadowedParameterDef(s,h),new hr(e,s,{metadata:o,def:h})}let p=e.lookupDefinition(s);if(!p||ie(p)&&p.value.isConstant){let d=e.context.lexicalScope;for(;d.noAutoDeclare&&d.parent;)d=d.parent;p=e._declareSymbolValue(s,{type:"unknown",inferred:!0},d)}return new hr(e,s,{metadata:o,def:p})}let u=n[s];if(u)return u;let l=e.lookupDefinition(s);if(ie(l)&&l.value.holdUntil==="never")return l.value.value??e.Nothing;if(l)return new hr(e,s,{metadata:o,def:l});let c=e.context.lexicalScope;for(;c.noAutoDeclare&&c.parent;)c=c.parent;return l=e._declareSymbolValue(s,{type:"unknown",inferred:!0},c),new hr(e,s,{metadata:o,def:l})}function UO(e,n,t,i){let r=i?.metadata;if(!VW(i?.canonical)&&Mr(t))return e._fn("Rational",[e.number(t[0]),e.number(t[1])],{...r,canonical:!1});let s=Nh(e,t);if(r===void 0){if(typeof s=="number"){let a=s;if(a===1)return e.One;if(a===0)return e.Zero;if(a===-1)return e.NegativeOne;if(a===2)return e.Two;if(Number.isInteger(a)&&n[a]!==void 0)return n[a]??=new An(e,s),n[a];if(Number.isNaN(a))return e.NaN;if(!Number.isFinite(a))return a<0?e.NegativeInfinity:e.PositiveInfinity}else if(s instanceof je){if(s.isZero)return e.Zero;if(s.isOne)return e.One;if(s.isNegativeOne)return e.NegativeOne;if(s.isNaN)return e.NaN;if(s.isNegativeInfinity)return e.NegativeInfinity;if(s.isPositiveInfinity)return e.PositiveInfinity}}return new An(e,s,{metadata:r})}var Nc=class{_rules;_cachedLength=-1;constructor(n){this._rules=n}get rules(){return this._rules}set rules(n){this._rules=n,this._cachedLength=-1}hasMutatedSinceLastCache(){return this._cachedLength>=0&&this._rules.length!==this._cachedLength}markCached(){this._cachedLength=this._rules.length}};var s0=class{_precision;_angularUnit;_tolerance;_bignumTolerance;_negBignumTolerance;constructor(n){let t=n?.precision??iy;t==="machine"&&(t=Math.floor(Qi)),this._precision=t,S.precision=t,this._angularUnit=n?.angularUnit??"rad",this._tolerance=ku,this._bignumTolerance=new S(ku),this._negBignumTolerance=new S(-ku),this.setTolerance(n?.tolerance??"auto")}get precision(){return this._precision}setPrecision(n){let t=n;if(t==="machine"&&(t=Qi),t==="auto"&&(t=iy),t===this._precision)return!1;if(typeof t!="number"||t<=0)throw Error('Expected "machine" or a positive number');return this._precision=Math.max(t,Qi),S.precision=this._precision,this.setTolerance("auto"),!0}get angularUnit(){return this._angularUnit}setAngularUnit(n){if(n===this._angularUnit)return!1;if(typeof n!="string")throw Error("Expected a string");return this._angularUnit=n,!0}get tolerance(){return this._tolerance}setTolerance(n){let t=n;t==="auto"&&(t=ku),(!Number.isFinite(t)||t<0)&&(t=Math.pow(10,-this._precision+2)),this._tolerance=t,this._bignumTolerance=new S(t),this._negBignumTolerance=new S(-t)}get bignumTolerance(){return this._bignumTolerance}get negBignumTolerance(){return this._negBignumTolerance}get bignumNaN(){return S.NAN}get bignumZero(){return S.ZERO}get bignumOne(){return S.ONE}get bignumTwo(){return S.TWO}get bignumHalf(){return S.HALF}get bignumPi(){return S.PI}get bignumNegativeOne(){return S.NEGATIVE_ONE}bignum(n){if(n instanceof S)return n;try{return new S(n)}catch(t){t instanceof Error?console.error(t.message):console.error(String(t))}return S.NAN}};var a0=class{_timeLimit=2e3;_iterationLimit=1024;_recursionLimit=256;_recursionDepth=0;_maxCollectionSize=1e4;_deadline=void 0;_isVerifying=!1;get timeLimit(){return this._timeLimit}set timeLimit(n){this._timeLimit=n<=0?Number.POSITIVE_INFINITY:n}get iterationLimit(){return this._iterationLimit}set iterationLimit(n){this._iterationLimit=n<=0?Number.POSITIVE_INFINITY:n}get recursionLimit(){return this._recursionLimit}set recursionLimit(n){this._recursionLimit=n<=0?Number.POSITIVE_INFINITY:n}get recursionDepth(){return this._recursionDepth}enterRecursion(){if(this._recursionDepth>=this._recursionLimit)throw new Ae({cause:"recursion-depth-exceeded",message:"Recursion limit exceeded"});this._recursionDepth+=1}exitRecursion(){this._recursionDepth>0&&(this._recursionDepth-=1)}get maxCollectionSize(){return this._maxCollectionSize}set maxCollectionSize(n){this._maxCollectionSize=n<=0?Number.POSITIVE_INFINITY:n}get deadline(){return this._deadline}set deadline(n){this._deadline=n}get timeRemaining(){return this._deadline===void 0?Number.POSITIVE_INFINITY:this._deadline-Date.now()}get isVerifying(){return this._isVerifying}set isVerifying(n){this._isVerifying=n}shouldContinueExecution(){return this._deadline===void 0||this._deadline>=Date.now()}};function JW(e){if(typeof e!="string")return P4(e),e;let n=Mb.find(t=>t.name===e);if(!n)throw new Error(`Unknown standard library: "${e}"`);return n}function ZO(e){return e?Cb(e.map(JW)):[...kb()]}function HO(e,n){for(let t of n){let i=t.definitions;if(!i)continue;let r=Array.isArray(i)?i:[i];for(let o of r)g4(e,o)}}function Nd(e,n){let t=e[n];if(!t)throw new Error(`Common symbol "${n}" failed to initialize`);return t}var u0=class{constructor(n){this.engine=n}engine;initializeCommonNumbers(){return{Zero:new An(this.engine,0),One:new An(this.engine,1),Half:new An(this.engine,{rational:[1,2]}),NegativeOne:new An(this.engine,-1),Two:new An(this.engine,2),NaN:new An(this.engine,Number.NaN),PositiveInfinity:new An(this.engine,Number.POSITIVE_INFINITY),NegativeInfinity:new An(this.engine,Number.NEGATIVE_INFINITY),I:new An(this.engine,{im:1}),ComplexInfinity:new An(this.engine,{re:1/0,im:1/0})}}bootstrapLibraries(n){let t=ZO(n);HO(this.engine,t)}initializeCommonSymbolBindings(n){return G6(this.engine,n),{True:Nd(n,"True"),False:Nd(n,"False"),Pi:Nd(n,"Pi"),E:Nd(n,"ExponentialE"),Nothing:Nd(n,"Nothing")}}};function jW(e){let n=[],t=e;for(;t;)t.types&&n.push(...Object.keys(t.types)),t=t.parent;return n}function zW(e,n){let t=e;for(;t;){if(t.types?.[n])return t.types[n];t=t.parent}}function YO(e){return{get names(){return jW(e.context.lexicalScope)},resolve(n){return zW(e.context.lexicalScope,n)},forward(n){let t={kind:"reference",name:n,alias:!1,def:void 0};return e.context.lexicalScope.types??={},e.context.lexicalScope.types[n]=t,t}}}function l0(e,n,t){let i;typeof n=="string"?i=e.string(n):i=e.function("ErrorCode",n.map(s=>e.string(s)));let r;t&&mm(t)?r=e.function("LatexString",[e.string(ys(t))]):typeof t=="string"&&t.length>0&&(r=e.string(t));let o=[e.expr(i)];return r&&o.push(r),e.function("Error",o)}function WO(e,n,t,i){return t?l0(e,["incompatible-type",le(n),t.toString()],i):l0(e,["incompatible-type",le(n)],i)}var GW=null;function c0(e){GW=e}var UW=/^(Sin|Cos|Tan|Cot|Sec|Csc)$/;function f0(e){return UW.test(e.operator)?!0:m(e)?e.ops.some(f0):!1}function aa(e,...n){return n.includes(e.operator)?!0:m(e)?e.ops.some(t=>aa(t,...n)):!1}function Tn(e,n){let t=e.engine;if(m(e)&&e.ops.length>0){let i=e,r=i.ops.map(s=>Tn(s,n));r.some((s,a)=>s!==i.ops[a])&&(e=t._fn(i.operator,r))}return n(e)??e}function uN(e,n){if(!m(e)||!m(n))return!1;let t=e.op1,i=n.op1;return t!==void 0&&i!==void 0&&t.isSame(i)}function ZW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(i){if(t==="Sec")return n.One.div(n._fn("Cos",[i]));if(t==="Csc")return n.One.div(n._fn("Sin",[i]))}}function n7(e){return Tn(e,ZW)}function HW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(i){if(t==="Tan")return n._fn("Sin",[i]).div(n._fn("Cos",[i]));if(t==="Cot")return n._fn("Cos",[i]).div(n._fn("Sin",[i]))}}function t7(e){return Tn(e,HW)}function YW(e){let n=e.engine;if(e.operator!=="Divide"||!m(e))return;let t=e.op1,i=e.op2;if(!(!t||!i)){if(t.operator==="Sin"&&i.operator==="Cos"&&uN(t,i))return m(t)?n._fn("Tan",[t.op1]):void 0;if(t.operator==="Cos"&&i.operator==="Sin"&&uN(t,i))return m(t)?n._fn("Cot",[t.op1]):void 0}}function i7(e){return Tn(e,YW)}function WW(e){if(m(e,"Negate"))return e.op1;if(m(e,"Multiply")){let n=e.ops.findIndex(t=>t.isSame(-1));if(n>=0){let t=e.ops.filter((i,r)=>r!==n);return t.length===1?t[0]:e.engine._fn("Multiply",t)}}}function QW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(!i)return;let r=WW(i);if(r){if(t==="Cos")return n._fn("Cos",[r]);if(t==="Sec")return n._fn("Sec",[r]);if(t==="Sin")return n._fn("Sin",[r]).neg();if(t==="Tan")return n._fn("Tan",[r]).neg();if(t==="Csc")return n._fn("Csc",[r]).neg();if(t==="Cot")return n._fn("Cot",[r]).neg()}}function r7(e){return Tn(e,QW)}function KW(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Sin"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.sub(n._fn("Cos",[r]).pow(2))}function lN(e){return Tn(e,KW)}function XW(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Cos"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.sub(n._fn("Sin",[r]).pow(2))}function o7(e){return Tn(e,XW)}function eQ(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Cos"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.add(n._fn("Cos",[r.mul(2)])).div(2)}function s7(e){return Tn(e,eQ)}function nQ(e){let n=e.engine;if(m(e,"Divide")){let i=e.op1,r=e.op2;if(!i||!r||!r.isSame(2))return;if(m(i,"Add")&&i.ops.length===2)return QO(n,i.ops)}let t=i=>!!(i.re===.5&&i.im===0||i.isSame(n.Half));if(m(e,"Multiply")){let i=e.ops.findIndex(r=>t(r));if(i>=0){let r=e.ops.filter((o,s)=>s!==i);if(r.length===1&&r[0].operator==="Add"){let o=r[0];if(m(o)&&o.ops.length===2)return QO(n,o.ops)}}}if(m(e,"Add")&&e.ops.length===2){let i,r,o=!1,s=a=>a.re===-.5&&a.im===0;for(let a of e.ops){if(t(a)){i=a;continue}let u=a,l=!1;if(m(a,"Negate")&&(l=!0,u=a.op1),m(u,"Divide")&&u.op2?.isSame(2)){let c=u.op1;if(c?.operator==="Cos"){r=c,o=l;continue}}if(m(u,"Multiply")){let c=u.ops.findIndex(p=>t(p));if(c>=0){let p=u.ops.filter((d,g)=>g!==c);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=l;continue}}let f=u.ops.findIndex(p=>s(p));if(f>=0){let p=u.ops.filter((d,g)=>g!==f);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=!l;continue}}}}if(i&&r){if(!m(r))return;let a=r.op1;if(!a)return;let u;if(m(a,"Multiply")){let l=a.ops.findIndex(c=>c.isSame(2));if(l>=0){let c=a.ops.filter((f,p)=>p!==l);u=c.length===1?c[0]:n._fn("Multiply",c)}}return u?o?n._fn("Sin",[u]).pow(2):n._fn("Cos",[u]).pow(2):void 0}}}function QO(e,n){let t=-1,i=-1,r=!1;for(let u=0;u<n.length;u++)if(n[u].isSame(1))t=u;else if(n[u].operator==="Cos")i=u,r=!1;else if(n[u].operator==="Negate"){let l=n[u];m(l)&&l.op1?.operator==="Cos"&&(i=u,r=!0)}if(t<0||i<0)return;let o;if(r){let u=n[i];if(!m(u))return;o=u.op1}else o=n[i];if(!m(o))return;let s=o.op1;if(!s)return;let a;if(m(s,"Multiply")){let u=s.ops.findIndex(l=>l.isSame(2));if(u>=0){let l=s.ops.filter((c,f)=>f!==u);a=l.length===1?l[0]:e._fn("Multiply",l)}}if(a)return r?e._fn("Sin",[a]).pow(2):e._fn("Cos",[a]).pow(2)}function cN(e){return Tn(e,nQ)}function tQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r];if(!m(o)||!m(s))continue;let a=o.op1,u=s.op1;if(!a||!u)continue;let l;if(o.operator==="Sin"&&s.operator==="Cos"?l=n._fn("Sin",[a.add(u)]).add(n._fn("Sin",[a.sub(u)])).div(2):o.operator==="Cos"&&s.operator==="Sin"?l=n._fn("Sin",[a.add(u)]).sub(n._fn("Sin",[a.sub(u)])).div(2):o.operator==="Cos"&&s.operator==="Cos"?l=n._fn("Cos",[a.add(u)]).add(n._fn("Cos",[a.sub(u)])).div(2):o.operator==="Sin"&&s.operator==="Sin"&&(l=n._fn("Cos",[a.sub(u)]).sub(n._fn("Cos",[a.add(u)])).div(2)),l){let c=t.filter((f,p)=>p!==i&&p!==r);return c.length===0?l:l.mul(c.length===1?c[0]:n._fn("Multiply",c))}}}function a7(e){return Tn(e,tQ)}function iQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r],a;if(o.operator==="Sin"&&s.operator==="Sin"){if(!m(o)||!m(s))continue;let u=o.op1,l=s.op1;if(u&&l){let c=u.add(l).div(2),f=u.sub(l).div(2);a=n._fn("Sin",[c]).mul(n._fn("Cos",[f])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Cos"){if(!m(o)||!m(s))continue;let u=o.op1,l=s.op1;if(u&&l){let c=u.add(l).div(2),f=u.sub(l).div(2);a=n._fn("Cos",[c]).mul(n._fn("Cos",[f])).mul(2)}}else if(o.operator==="Sin"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Sin")continue;let u=s.op1;if(!m(u))continue;let l=o.op1,c=u.op1;if(l&&c){let f=l.add(c).div(2),p=l.sub(c).div(2);a=n._fn("Cos",[f]).mul(n._fn("Sin",[p])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Cos")continue;let u=s.op1;if(!m(u))continue;let l=o.op1,c=u.op1;if(l&&c){let f=l.add(c).div(2),p=l.sub(c).div(2);a=n._fn("Sin",[f]).mul(n._fn("Sin",[p])).mul(-2)}}if(a){let u=t.filter((l,c)=>c!==i&&c!==r);return u.length===0?a:a.add(u.length===1?u[0]:n._fn("Add",u))}}}function p0(e){return Tn(e,iQ)}function rQ(e){let n=e.engine,t=e.operator;if(t!=="Sin"&&t!=="Cos"||!m(e))return;let i=e.op1;if(i){if(m(i,"Add")&&i.ops.length===2){let[r,o]=i.ops;return t==="Sin"?n._fn("Sin",[r]).mul(n._fn("Cos",[o])).add(n._fn("Cos",[r]).mul(n._fn("Sin",[o]))):n._fn("Cos",[r]).mul(n._fn("Cos",[o])).sub(n._fn("Sin",[r]).mul(n._fn("Sin",[o])))}if(m(i,"Subtract")){let r=i.op1,o=i.op2;return!r||!o?void 0:t==="Sin"?n._fn("Sin",[r]).mul(n._fn("Cos",[o])).sub(n._fn("Cos",[r]).mul(n._fn("Sin",[o]))):n._fn("Cos",[r]).mul(n._fn("Cos",[o])).add(n._fn("Sin",[r]).mul(n._fn("Sin",[o])))}}}function u7(e){return Tn(e,rQ)}function oQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r],a=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Sin"&&k.operator==="Cos"?{sin:T,cos:k}:T.operator==="Cos"&&k.operator==="Sin"?{sin:k,cos:T}:null},u=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Cos"&&k.operator==="Cos"?{cos1:T,cos2:k}:null},l=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Sin"&&k.operator==="Sin"?{sin1:T,sin2:k}:null},c=_=>m(_)?_.op1:void 0,f=a(o),p=a(s),d=m(o,"Negate")&&o.op1?a(o.op1):null,g=m(s,"Negate")&&s.op1?a(s.op1):null;if(f&&p){let _=c(f.sin),I=c(f.cos),T=c(p.sin),k=c(p.cos);if(_&&I&&T&&k&&_.isSame(k)&&I.isSame(T)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(f&&g){let _=c(f.sin),I=c(f.cos),T=c(g.sin),k=c(g.cos);if(_&&I&&T&&k&&_.isSame(k)&&I.isSame(T)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(d&&p){let _=c(d.sin),I=c(d.cos),T=c(p.sin),k=c(p.cos);if(_&&I&&T&&k&&T.isSame(I)&&k.isSame(_)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[T.sub(k)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}let h=u(o),b=u(s),y=l(o),x=l(s),E=m(o,"Negate")&&o.op1?l(o.op1):null,v=m(s,"Negate")&&s.op1?l(s.op1):null;if(h&&v){let _=c(h.cos1),I=c(h.cos2),T=c(v.sin1),k=c(v.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(E&&b){let _=c(b.cos1),I=c(b.cos2),T=c(E.sin1),k=c(E.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(h&&x){let _=c(h.cos1),I=c(h.cos2),T=c(x.sin1),k=c(x.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(y&&b){let _=c(b.cos1),I=c(b.cos2),T=c(y.sin1),k=c(y.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}}}function d0(e){return Tn(e,oQ)}function sQ(e){let n=e.engine,t=e.operator;if(t!=="Sin"&&t!=="Cos"||!m(e))return;let i=e.op1;if(i&&m(i,"Multiply")){let r=i.ops,o=r.findIndex(s=>s.isSame(2));if(o>=0){let s=r.filter((u,l)=>l!==o),a=s.length===1?s[0]:n._fn("Multiply",s);return t==="Sin"?n._fn("Sin",[a]).mul(n._fn("Cos",[a])).mul(2):n._fn("Cos",[a]).pow(2).mul(2).sub(n.One)}}}function fN(e){return Tn(e,sQ)}function aQ(e){let n=e.engine;if(m(e,"Multiply")){let t=e.ops,i=t.findIndex(r=>r.isSame(2));if(i>=0){let r=t.filter((a,u)=>u!==i),o,s;for(let a of r)a.operator==="Sin"&&!o?o=a:a.operator==="Cos"&&!s&&(s=a);if(o&&s&&uN(o,s)){if(!m(o))return;let a=r.filter(l=>l!==o&&l!==s),u=n._fn("Sin",[o.op1.mul(2)]);return a.length===0?u:u.mul(a.length===1?a[0]:n._fn("Multiply",a))}}}if(m(e,"Add")&&e.ops.length===2){let[t,i]=e.ops;if(m(t,"Power")&&t.op1?.operator==="Cos"&&t.op2?.isSame(2)&&i.operator==="Negate"&&m(i)&&i.op1?.operator==="Power"&&m(i.op1)&&i.op1.op1?.operator==="Sin"&&i.op1.op2?.isSame(2)){let u=t.op1,l=i.op1;if(m(u)&&m(l)){let c=l.op1;if(m(c)){let f=u.op1,p=c.op1;if(f&&p&&f.isSame(p))return n._fn("Cos",[f.mul(2)])}}}let r=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Cos"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}},o=r(t);if(o&&(i.isSame(-1)||m(i,"Negate")&&i.op1?.isSame(1)))return n._fn("Cos",[o.mul(2)]);if(o=r(i),o&&(t.isSame(-1)||m(t,"Negate")&&t.op1?.isSame(1)))return n._fn("Cos",[o.mul(2)]);let s=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Sin"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}};if(t.isSame(1)&&m(i,"Negate")&&i.op1){let u=s(i.op1);if(u)return n._fn("Cos",[u.mul(2)])}if(i.isSame(1)&&m(t,"Negate")&&t.op1){let u=s(t.op1);if(u)return n._fn("Cos",[u.mul(2)])}let a=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(-2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Sin"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}};if(t.isSame(1)){let u=a(i);if(u)return n._fn("Cos",[u.mul(2)])}if(i.isSame(1)){let u=a(t);if(u)return n._fn("Cos",[u.mul(2)])}}}function l7(e){return Tn(e,aQ)}function KO(e){let n=!1,t=e;if(m(t,"Negate")&&t.op1)n=!0,t=t.op1;else if(m(t,"Multiply")&&t.ops.length===2){let s=t.ops.findIndex(a=>a.isSame(-1));s>=0&&(n=!0,t=t.ops[1-s])}if(!m(t,"Power"))return;let i=t.op1,r=t.op2;if(!i||!r||!(r.isSame(2)||r.isSame(4))||i.operator!=="Sin"&&i.operator!=="Cos"||!m(i))return;let o=i.op1;if(o)return{func:i.operator,arg:o,power:r.isSame(2)?2:4,negated:n}}function uQ(e){let n=e.engine;if(!m(e,"Add")||e.ops.length!==2)return;let t=KO(e.ops[0]),i=KO(e.ops[1]);if(!t||!i||t.negated===i.negated||t.func===i.func||t.power!==i.power||!t.arg.isSame(i.arg))return;let r=t.negated?i:t,o=n._fn("Cos",[r.arg.mul(2)]);return r.func==="Cos"?o:o.neg()}function c7(e){return Tn(e,uQ)}function lQ(e){let n=e.engine;if(e.operator!=="Tan"||!m(e))return;let t=e.op1;if(t){if(m(t,"Add")&&t.ops.length===2){let[i,r]=t.ops,o=n._fn("Tan",[i]),s=n._fn("Tan",[r]);return o.add(s).div(n.One.sub(o.mul(s)))}if(m(t,"Subtract")){let i=t.op1,r=t.op2;if(!i||!r)return;let o=n._fn("Tan",[i]),s=n._fn("Tan",[r]);return o.sub(s).div(n.One.add(o.mul(s)))}}}function f7(e){return Tn(e,lQ)}var cQ=[{value:0,angle:[0,1]},{value:1/Math.sqrt(3),angle:[1,6]},{value:1,angle:[1,4]},{value:Math.sqrt(3),angle:[1,3]},{value:2-Math.sqrt(3),angle:[1,12]},{value:2+Math.sqrt(3),angle:[5,12]}];function fQ(e,n=1e-10){for(let t of cQ)if(Math.abs(t.value-e)<n)return t.angle}function pQ(e){if(e.operator!=="Multiply"||!m(e))return;let n=e.ops;if(n.length<2)return;let t=[],i=1;for(let r of n)if(m(r,"Tan")&&r.op1)t.push(r.op1);else if(m(r,"Negate")&&r.op1?.operator==="Sqrt"){let o=r.op1;if(m(o)){let s=o.op1;if(N(s)&&typeof s.re=="number")i*=-Math.sqrt(s.re);else return}else return}else if(m(r,"Sqrt")){let o=r.op1;if(o&&N(o)&&typeof o.re=="number")i*=Math.sqrt(o.re);else return}else if(N(r)&&typeof r.re=="number")i*=r.re;else return;if(t.length===2)return[i,t[0],t[1]]}function XO(e){if(m(e,"Multiply")){let n=!1,t;for(let i of e.ops)if(w(i,"Pi"))n=!0;else if(N(i)&&typeof i.re=="number"){let r=i.re;for(let o=1;o<=36;o++){let s=Math.round(r*o);if(Math.abs(s/o-r)<1e-10){t=[s,o];break}}}if(n&&t)return t}if(w(e,"Pi"))return[1,1]}function dQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length!==3)return;let i=[],r;for(let x=0;x<t.length;x++){let E=t[x];if(m(E,"Tan")&&E.op1)i.push({arg:E.op1,index:x});else{let v=pQ(E);v&&(r={coef:v[0],arg1:v[1],arg2:v[2],index:x})}}if(i.length!==2||!r)return;let[o,s]=i,a=o.arg.isSame(r.arg1)||o.arg.isSame(r.arg2),u=s.arg.isSame(r.arg1)||s.arg.isSame(r.arg2),l=o.arg.isSame(r.arg2)||o.arg.isSame(r.arg1),c=s.arg.isSame(r.arg2)||s.arg.isSame(r.arg1);if(!(a&&c||u&&l))return;let f=-r.coef;if(f<=0)return;let p=fQ(f);if(!p)return;let d=XO(o.arg),g=XO(s.arg);if(!d||!g)return;let h=e7(e7(d[1],g[1]),p[1]);if(d[0]*(h/d[1])+g[0]*(h/g[1])+p[0]*(h/p[1])!==h)return;let y=n._fn("Multiply",[n.number([p[0],p[1]]),n.symbol("Pi")]);return n._fn("Tan",[y]).neg()}function e7(e,n){return Math.abs(e*n)/mQ(e,n)}function mQ(e,n){for(e=Math.abs(e),n=Math.abs(n);n;){let t=n;n=e%n,e=t}return e}function p7(e){return Tn(e,dQ)}function gQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r];if(!m(o)||!m(s))continue;let a=o.op1,u=s.op1;if(!(!a||!u)){if(o.operator==="Tan"&&s.operator==="Tan"){let l=o,c=s,f=n._fn("Cot",[a.add(u)]),p=n.One.sub(l.add(c).mul(f)),d=t.filter((g,h)=>h!==i&&h!==r);return d.length===0?p:p.mul(d.length===1?d[0]:n._fn("Multiply",d))}if(o.operator==="Cot"&&s.operator==="Cot"){let l=o,c=s,f=n._fn("Cot",[a.add(u)]),p=n.One.add(l.add(c).mul(f)),d=t.filter((g,h)=>h!==i&&h!==r);return d.length===0?p:p.mul(d.length===1?d[0]:n._fn("Multiply",d))}}}}function d7(e){return Tn(e,gQ)}function hQ(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||!i.isSame(2)||!m(t))return;let r=t.op1;if(r){if(t.operator==="Tan")return n._fn("Sec",[r]).pow(2).sub(n.One);if(t.operator==="Cot")return n._fn("Csc",[r]).pow(2).sub(n.One);if(t.operator==="Sec")return n.One.add(n._fn("Tan",[r]).pow(2));if(t.operator==="Csc")return n.One.add(n._fn("Cot",[r]).pow(2))}}function m7(e){return Tn(e,hQ)}function bQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length!==2)return;let i=p=>{let d=!1,g=p;if(m(p,"Negate")&&(d=!0,g=p.op1),!m(g)||g.operator!=="Power"||!g.op2?.isSame(2))return null;let h=g.op1;if(!m(h)||!h.op1)return null;let b=h.operator;return["Tan","Cot","Sec","Csc"].includes(b)?{func:b,arg:h.op1,neg:d}:null},r=i(t[0]),o=i(t[1]);if(r&&o&&r.arg.isSame(o.arg)){if(r.func==="Cot"&&!r.neg&&o.func==="Csc"&&o.neg||r.func==="Csc"&&r.neg&&o.func==="Cot"&&!o.neg)return n.number(-1);if(r.func==="Csc"&&!r.neg&&o.func==="Cot"&&o.neg||r.func==="Cot"&&r.neg&&o.func==="Csc"&&!o.neg)return n.One;if(r.func==="Tan"&&!r.neg&&o.func==="Sec"&&o.neg||r.func==="Sec"&&r.neg&&o.func==="Tan"&&!o.neg)return n.number(-1);if(r.func==="Sec"&&!r.neg&&o.func==="Tan"&&o.neg||r.func==="Tan"&&r.neg&&o.func==="Sec"&&!o.neg)return n.One}let s=-1,a=-1,u=!1;for(let p=0;p<t.length;p++){let d=t[p];d.isSame(1)?(s=p,u=!1):d.isSame(-1)||m(d,"Negate")&&d.op1?.isSame(1)?(s=p,u=!0):m(d,"Power")&&d.op2?.isSame(2)&&(a=p)}if(s<0||a<0)return;let l=t[a];if(!m(l))return;let c=l.op1;if(!c||!m(c))return;let f=c.op1;if(f){if(c.operator==="Sec"&&u)return n._fn("Tan",[f]).pow(2);if(c.operator==="Csc"&&u)return n._fn("Cot",[f]).pow(2);if(c.operator==="Tan"&&!u)return n._fn("Sec",[f]).pow(2);if(c.operator==="Cot"&&!u)return n._fn("Csc",[f]).pow(2)}}function pN(e){return Tn(e,bQ)}function yQ(e){let n=e.engine;if(!m(e,"Multiply"))return[1,n.One,e];for(let t=0;t<e.ops.length;t++){let i=e.ops[t],r;if(N(i)&&typeof i.re=="number"&&i.im===0&&(r=i.re),r!==void 0){let o=e.ops.filter((a,u)=>u!==t),s=o.length===1?o[0]:n._fn("Multiply",o);return[r,i,s]}}return[1,n.One,e]}function xQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(t.length<2)return;let i=[],r=[];for(let T of t)if(m(T,"Cos")&&T.op1){let k=yQ(T.op1);k?i.push({arg:k[2],numericMult:k[0],symbolicCoeff:k[1]}):i.push({arg:T.op1,numericMult:1,symbolicCoeff:n.One})}else r.push(T);if(i.length<2)return;let o=i[0].arg,s=i.filter(T=>T.arg.isSame(o)),a=i.filter(T=>!T.arg.isSame(o));if(s.length<2)return;s.sort((T,k)=>T.numericMult-k.numericMult);let u=[],l=[],c=[...s],f=c[0].numericMult;if(f>0){u.push(c[0]);let T=new Set([0]),k=f*2;for(;;){let A=c.findIndex((P,B)=>!T.has(B)&&Math.abs(P.numericMult-k)<1e-10);if(A===-1)break;u.push(c[A]),T.add(A),k*=2}l=c.filter((A,P)=>!T.has(P))}if(u.length<2)return;let p=u[0].numericMult,d=[...r];for(let T of l){let k=T.symbolicCoeff.isSame(n.One)?T.arg:n._fn("Multiply",[T.symbolicCoeff,T.arg]);d.push(n._fn("Cos",[k]))}for(let T of a){let k=T.symbolicCoeff.isSame(n.One)?T.arg:n._fn("Multiply",[T.symbolicCoeff,T.arg]);d.push(n._fn("Cos",[k]))}let g=u.length,h=u[0].symbolicCoeff,b=Math.pow(2,g);if(w(o,"Pi")){let T=1/(b+1);if(Math.abs(p-T)<1e-10){let k=n.number([1,b]);return d.length===0?k:k.mul(d.length===1?d[0]:n._fn("Multiply",d))}}let y=h.mul(b),x=h.isSame(n.One)?o:n._fn("Multiply",[h,o]),E=n._fn("Multiply",[y,o]),v=n._fn("Sin",[E]),_=n._fn("Sin",[x]),I=v.div(n.number(b).mul(_));return d.length===0?I:I.mul(d.length===1?d[0]:n._fn("Multiply",d))}function g7(e){return Tn(e,xQ)}function EQ(e){if(m(e,"Power")&&e.op2?.isSame(2)){let n=e.op1;if(m(n,"Sin")&&n.op1)return{func:"Sin",arg:n.op1,coef:1};if(m(n,"Cos")&&n.op1)return{func:"Cos",arg:n.op1,coef:1}}if(m(e,"Multiply")){let n=1,t;for(let i of e.ops)if(m(i,"Power")&&i.op2?.isSame(2)){let r=i.op1;(r?.operator==="Sin"||r?.operator==="Cos")&&(t=i)}else typeof i.re=="number"&&i.im===0&&(n*=i.re);if(m(t)){let i=t.op1;if(m(i,"Sin")&&i.op1)return{func:"Sin",arg:i.op1,coef:n};if(m(i,"Cos")&&i.op1)return{func:"Cos",arg:i.op1,coef:n}}}return null}function vQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length<2)return;let i=[],r=[],o=[];for(let s=0;s<t.length;s++){let a=t[s],u=EQ(a);u?i.push({...u,index:s}):typeof a.re=="number"&&a.im===0&&N(a)?o.push({value:a.re,index:s}):r.push({expr:a,index:s})}for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let u=i[s],l=i[a];if(u.arg.isSame(l.arg)&&(u.func==="Sin"&&l.func==="Cos"||u.func==="Cos"&&l.func==="Sin")&&Math.abs(u.coef-l.coef)<1e-10){let c=u.coef,f=new Set([u.index,l.index]),p=t.filter((d,g)=>!f.has(g));return p.length===0?n.number(c):c===1?n._fn("Add",[n.One,...p]):n._fn("Add",[n.number(c),...p])}}for(let s of i)if(s.coef<0){let a=Math.abs(s.coef);for(let u of o)if(Math.abs(u.value-a)<1e-10){let l=new Set([s.index,u.index]),c=t.filter((d,g)=>!l.has(g)),f=s.func==="Sin"?"Cos":"Sin",p=n._fn(f,[s.arg]).pow(2).mul(a);return c.length===0?p:n._fn("Add",[p,...c])}}}function h7(e){return Tn(e,vQ)}var SQ=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]);function dN(e){let n=0;if(SQ.has(e.operator)&&(n=1),m(e))for(let t of e.ops)n+=dN(t);return n}function mN(e){if(w(e)||N(e))return 1;let n=1;if(m(e))for(let t of e.ops)n+=mN(t);return n}function b7(e){let n=dN(e),t=mN(e);return n*1e3+t}var y7=b7;function gN(e,n){if(e.length===0)throw new Error("bestOf called with empty array");if(e.length===1)return e[0];let t=e[0],i=n(t);for(let r=1;r<e.length;r++){let o=n(e[r]);o<i&&(t=e[r],i=o)}return t}function wd(e,n){let t=n(e);return t.isSame(e)?null:t}function x7(e,n){let t=wd(e,lN),i=wd(e,o7),r=[e];return t&&r.push(t),i&&r.push(i),gN(r,n)}function _Q(e,n){return x7(e,n)}function NQ(e,n){let t=wd(e,a7),i=[e];if(t){i.push(t);let r=wd(t,d0);r&&i.push(r)}return gN(i,n)}function wQ(e,n){let t=wd(e,d0),i=[e];return t&&i.push(t),gN(i,n)}function IQ(e,n){let t=f7(e);return t=d7(t),t}function TQ(e,n){let t=e;return t=u7(t),t=fN(t),t=lN(t),t=s7(t),t=fN(t),t=NQ(t,n),t=x7(t,n),t=p0(t),t=_Q(t,n),t=p0(t),t=wQ(t,n),t}function E7(e,n){if(!f0(e))return;let t=n?.measure??y7,i=n?.maxIterations??100,r=e,o=0,s=e,a=t(e),u=_=>{let I=t(_);I<a&&(s=_,a=I)};r=r7(r),u(r);let l=pN(r);u(l);let c=m7(r);u(c),r=s;let f=cN(r);if(u(f),r=s,aa(r,"Sec","Csc")&&(r=n7(r),s=r,a=t(r)),aa(r,"Tan","Cot")){let _=IQ(r,t);u(_),r=_}if(aa(r,"Tan","Cot")&&(r=t7(r),u(r)),aa(r,"Sin","Cos")){let _=p0(r);u(_),r=s}if(aa(r,"Sin","Cos")){let _=t(r);for(;o<i;){o++;let I=TQ(r,t),T=t(I);if(u(I),T>=_)break;r=I,_=T}}let p=i7(s);u(p);let d=l7(s);u(d);let g=c7(s);u(g);let h=g7(s);u(h);let b=cN(s);u(b);let y=pN(s);u(y);let x=d0(s);u(x);let E=h7(s);u(E);let v=p7(s);if(u(v),s.operator==="Add"||s.operator==="Multiply"){let _=e.engine.expr(s.json);u(_)}if(!s.isSame(e))return{value:s,because:"fu"}}function hN(e,n){if(Array.isArray(e)){if(e[0]==="InvisibleOperator")for(let t=1;t+1<e.length;t++){let i=e[t],r=e[t+1];typeof i=="string"&&Array.isArray(r)&&r[0]==="Delimiter"&&n.add(i)}for(let t of e)hN(t,n);return}e!==null&&typeof e=="object"&&"fn"in e&&Array.isArray(e.fn)&&hN(e.fn,n)}var yo=class e{static _latexSyntaxFactory=null;True;False;Pi;E;Nothing;Zero;One;Half;NegativeOne;Two;I;NaN;PositiveInfinity;NegativeInfinity;ComplexInfinity;_numericConfiguration;_cacheStore=new $b;_runtimeState=new a0;_configurationLifecycle=new o0;_cost;_randomSeed=null;_rng;_integrationProvider;_simplificationRules=new Nc([...e6]);_solveRules=new Nc([...nR]);_harmonizationRules=new Nc([...oR]);_compilationTargets=new i0;_fuAlgorithm=E7;_commonSymbols={Pi:null,True:null,False:null,All:null,Nothing:null,None:null,Undefined:null,ImaginaryUnit:null,ExponentialE:null};_commonNumbers={"-5":null,"-4":null,"-3":null,"-2":null,2:null,3:null,4:null,5:null,6:null,7:null,8:null,9:null,10:null,11:null,12:null,36:null};_evalContextStack=[];get context(){return this._evalContextStack[this._evalContextStack.length-1]}get contextStack(){return[...this._evalContextStack]}set contextStack(n){this._evalContextStack=[...n]}__typeResolver;get _typeResolver(){return this.__typeResolver??=YO(this),this.__typeResolver}declareType(n,t,i){f6(this,n,t,i)}get trace(){return this._evalContextStack.map(n=>n.name).filter(n=>n!==void 0).reverse()}get _generation(){return this._configurationLifecycle.generation}set _generation(n){this._configurationLifecycle.generation=n}get _mutationGeneration(){return this._configurationLifecycle.mutationGeneration}set _mutationGeneration(n){this._configurationLifecycle.mutationGeneration=n}get _ephemeralWriteDepth(){return this._configurationLifecycle.ephemeralWriteDepth}set _ephemeralWriteDepth(n){this._configurationLifecycle.ephemeralWriteDepth=n}_inferenceTxDepth=0;_freshlyInferred=null;strict;static getStandardLibrary(n){return kb(n)}constructor(n){if(n!==void 0&&typeof n!="object")throw Error("Unexpected argument");this.strict=!0,this._numericConfiguration=new s0({precision:n?.precision,tolerance:n?.tolerance??"auto",angularUnit:"rad"});let t=new u0(this),i=t.initializeCommonNumbers();this.Zero=i.Zero,this.One=i.One,this.Half=i.Half,this.NegativeOne=i.NegativeOne,this.Two=i.Two,this.NaN=i.NaN,this.PositiveInfinity=i.PositiveInfinity,this.NegativeInfinity=i.NegativeInfinity,this.I=i.I,this.ComplexInfinity=i.ComplexInfinity,this._reset(),this.pushScope(void 0,"system"),this.declareType("limits","expression<Limits>"),this.declareType("distribution","expression<NormalDistribution> | expression<BinomialDistribution> | expression<PoissonDistribution> | expression<UniformDistribution> | expression<ExponentialDistribution>",{alias:!0}),t.bootstrapLibraries(n?.libraries);let r=t.initializeCommonSymbolBindings(this._commonSymbols);this.True=r.True,this.False=r.False,this.Pi=r.Pi,this.E=r.E,this.Nothing=r.Nothing,this.pushScope(void 0,"global"),this._compilationTargets.registerDefaults(),n?.latexSyntax&&(this._latexSyntax=n.latexSyntax),n?.latexOptions&&(this._latexOptions={...n.latexOptions}),Ew(this)}toJSON(){return"[ComputeEngine]"}[Symbol.toStringTag]="ComputeEngine";_reset(){this._configurationLifecycle.reset({refreshNumericConstants:()=>{},resetCommonSymbols:()=>U6(this._commonSymbols),purgeCaches:()=>this._cacheStore.purgeValues()})}listenToConfigurationChange(n){return this._configurationLifecycle.listen(n)}_compile(n,t){return dd(n,t)}getCompilationTarget(n){return this._compilationTargets.get(n)}listCompilationTargets(){return this._compilationTargets.list()}registerCompilationTarget(n,t){this._compilationTargets.register(n,t)}unregisterCompilationTarget(n){this._compilationTargets.unregister(n)}get precision(){return this._numericConfiguration.precision}set precision(n){this._numericConfiguration.setPrecision(n)&&this._reset()}get angularUnit(){return this._numericConfiguration.angularUnit}set angularUnit(n){this._numericConfiguration.setAngularUnit(n)&&this._reset()}get timeLimit(){return this._runtimeState.timeLimit}set timeLimit(n){this._runtimeState.timeLimit=n}withTimeLimit(n,t){let i=this._runtimeState.deadline,r=Date.now()+n;this._runtimeState.deadline=i===void 0?r:Math.min(i,r);try{return t()}finally{this._runtimeState.deadline=i}}get deadline(){return this._runtimeState.deadline}set deadline(n){this._runtimeState.deadline=n}get _deadline(){return this._runtimeState.deadline}set _deadline(n){this._runtimeState.deadline=n}get _timeRemaining(){return this._runtimeState.timeRemaining}get iterationLimit(){return this._runtimeState.iterationLimit}set iterationLimit(n){this._runtimeState.iterationLimit=n}get recursionLimit(){return this._runtimeState.recursionLimit}set recursionLimit(n){this._runtimeState.recursionLimit=n}_enterRecursion(){this._runtimeState.enterRecursion()}_exitRecursion(){this._runtimeState.exitRecursion()}get maxCollectionSize(){return this._runtimeState.maxCollectionSize}set maxCollectionSize(n){this._runtimeState.maxCollectionSize=n}get _isVerifying(){return this._runtimeState.isVerifying}set _isVerifying(n){this._runtimeState.isVerifying=n}get isVerifying(){return this._runtimeState.isVerifying}get tolerance(){return this._numericConfiguration.tolerance}set tolerance(n){this._numericConfiguration.setTolerance(n)}get randomSeed(){return this._randomSeed}set randomSeed(n){this._randomSeed=n,this._rng=n===null?void 0:dp(Zx(n))}_random(){return this._rng?this._rng():Math.random()}_randomNumericSeed(){return this._randomSeed===null?null:Zx(this._randomSeed)}chop(n){let t=this._numericConfiguration.tolerance;return typeof n=="number"?Math.abs(n)<=t?0:n:n instanceof S?n.isPositive()&&n.lte(this._numericConfiguration.bignumTolerance)||n.isNegative()&&n.gte(this._numericConfiguration.negBignumTolerance)||n.isZero()?0:n:n instanceof L&&Math.abs(n.re)<=t&&Math.abs(n.im)<=t?0:n}bignum(n){return this._numericConfiguration.bignum(n)}complex(n,t){return n instanceof S&&(n=n.toNumber()),t instanceof S&&(t=t.toNumber()),new L(n,t)}_numericValue(n){if(n instanceof je)return n.asExact??n;let t=this._numericConfiguration.precision>Qi?i=>new Ba(i):i=>new qo(i);if(typeof n=="number")return Number.isInteger(n)?new Ne(n,t):t(n);if(typeof n=="bigint")return new Ne(n,t);if(Mr(n))return new Ne({rational:n},t);if(n instanceof S){if(n.isInteger()){let i=ln(n.toString());if(i!==null)return new Ne(i,t)}return t(n)}if(n instanceof L)return n.im===0?this._numericValue(n.re):t({re:n.re,im:n.im});if("im"in n||"re"in n)return n.im!==void 0&&n.im!==0?t(n):n.re instanceof S&&n.re.isInteger()?new Ne({rational:[ln(n.re.toString()),BigInt(1)]},t):typeof n.re=="number"&&Number.isInteger(n.re)?new Ne({rational:[n.re,1]},t):t(n);if("radical"in n||"rational"in n){let i=n;if(i.radical!==void 0&&i.radical!==1){if(!Number.isInteger(i.radical)||i.radical<1)return t({re:Vu(i.rational??[1,1])*Math.sqrt(i.radical)});if(i.radical>=Se){let[r,o]=Di(i.radical,2);if(o>=Se)return t({re:Vu(i.rational??[1,1])*Math.sqrt(i.radical)});i={...i,radical:o,rational:Ue(i.rational??[1,1],[r,1])}}}return i.rational&&Wn(i.rational)&&(!Number.isInteger(i.rational[0])||!Number.isInteger(i.rational[1]))?t(i):new Ne(i,t)}throw Error(`Unexpected value: ${typeof n=="object"?JSON.stringify(n):String(n)}`)}get costFunction(){return this._cost??h4}set costFunction(n){this._cost=typeof n=="function"?n:void 0}get simplificationRules(){return this._simplificationRules.rules}set simplificationRules(n){this._simplificationRules.rules=n,this._cacheStore.invalidate("standard-simplification-rules")}get solveRules(){return this._solveRules.rules}set solveRules(n){this._solveRules.rules=n,this._cacheStore.invalidate("univariate-roots-rules")}get harmonizationRules(){return this._harmonizationRules.rules}set harmonizationRules(n){this._harmonizationRules.rules=n,this._cacheStore.invalidate("harmonization-rules")}lookupDefinition(n){return r6(this,n)}normalizeIdentifier(n){if(!n)return"";if(yn(n))return n;this.pushScope();try{let t=this.parse(n);if(w(t))return t.symbol}finally{this.popScope()}return""}operatorInfo(n){let t=this.lookupDefinition(n);if(!t||!fe(t))return;let i=t.operator,r=!!(i.evaluate||i.collection);return{kind:r?"function":"opaque",signature:i.signature,canEvaluate:r}}symbolInfo(n){let t=this.lookupDefinition(n);if(!t||!ie(t))return;let i=t.value;return{kind:i.isConstant?"constant":"variable",type:i.type}}searchDefinitions(n,t){return o6(this,n,t)}suggestOperatorName(n){return s6(this,n)}functionProperties(n){return nu(this,n)}_declareSymbolValue(n,t,i){return a6(this,n,t,i)}_declareSymbolOperator(n,t,i){return u6(this,n,t,i)}pushScope(n,t){b6(this,n,t)}popScope(){y6(this)}_pushEvalContext(n,t){dS(this,n,t)}_popEvalContext(){mS(this)}_inScope(n,t){return x6(this,n,t)}_printStack(n){E6(this,n)}_shadowedParameterStack=[];_pushShadowedParameters(n,t){this._shadowedParameterStack.push({names:new Set(n),types:t,defs:new Map})}_popShadowedParameters(){this._shadowedParameterStack.pop()}_isShadowedParameter(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return!0;return!1}_shadowedParameterType(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return t[i].types?.get(n)}_shadowedParameterDef(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return t[i].defs.get(n)}_setShadowedParameterDef(n,t){let i=this._shadowedParameterStack;for(let r=i.length-1;r>=0;r--)if(i[r].names.has(n)){i[r].defs.set(n,t);return}}_getSymbolValue(n){return l6(this,n)}_setSymbolValue(n,t){c6(this,n,t)}declare(n,t,i){return p6(this,n,t,i)}declareSequence(n,t){return D6(this,n,t)}getSequenceStatus(n){return O6(this,n)}getSequence(n){return L6(this,n)}listSequences(){return F6(this)}isSequence(n){return B6(this,n)}clearSequenceCache(n){$6(this,n)}getSequenceCache(n){return q6(this,n)}getSequenceTerms(n,t,i,r){return V6(this,n,t,i,r)}lookupOEIS(n,t){return J6(this,n,t)}checkSequenceOEIS(n,t,i){return j6(this,n,t,i)}interpret(n,t){return z6(this,n,t)}assign(n,t){return d6(this,n,t)}_shouldContinueExecution(){return this._runtimeState.shouldContinueExecution()}_checkContinueExecution(){if(!this._shouldContinueExecution())throw new Error("timeout")}_cache(n,t,i){return this._cacheStore.getOrBuild(n,t,i)}expr(n,t){let{canonical:i,structural:r}=Pb(t);return Yt(this,n,{canonical:i,structural:r,scope:t?.scope})}box(n,t){return this.expr(n,t)}_latexSyntax;get latexSyntax(){return!this._latexSyntax&&e._latexSyntaxFactory&&(this._latexSyntax=e._latexSyntaxFactory()),this._latexSyntax}_requireLatexSyntax(){if(!this._latexSyntax&&e._latexSyntaxFactory&&(this._latexSyntax=e._latexSyntaxFactory()),!this._latexSyntax)throw new Error("LatexSyntax not available. Pass a LatexSyntax instance to the ComputeEngine constructor.");return this._latexSyntax}_latexOptions={};get latexOptions(){return this._latexOptions}set latexOptions(n){this._latexOptions={...n}}parse(n,t){if(n==null)return null;if(typeof n!="string")throw Error("ce.parse(): expected a LaTeX string");let i=this._requireLatexSyntax(),{form:r,canonical:o,structural:s,...a}=t??{},u=a.diagnostics??this._latexOptions?.diagnostics??!1,l,c,f,p=new Set;if(u){l=[],f=g=>p.add(g);let d=new Set;c=g=>{let h=`${g.code} ${g.start} ${g.end} ${g.detail?JSON.stringify(g.detail):""}`;d.has(h)||(d.add(h),l.push(g))}}tS(this);try{let d=i.parse(n,{getSymbolType:h=>{let b=this.lookupDefinition(h);return b?fe(b)?b.operator.signature:ie(b)?b.value.type:Z.unknown:Z.unknown},hasSubscriptEvaluate:h=>{let b=this.lookupDefinition(h);return!!(ie(b)&&b.value.subscriptEvaluate)},isSymbolDeclared:h=>!!this.lookupDefinition(h),tolerance:this.tolerance,...this._latexOptions,...a,diagnostics:u,onDiagnostic:c,onBoundVariable:f});if(d===null)return null;let g=Yt(this,d,Pb({form:r,canonical:o,structural:s}));if(l!==void 0){if(g=g._unshared(),g.isCanonical)try{let h=new Set(g.symbols),b=new Set(g.freeVariables);for(let y of l){if(y.code!=="undeclared-symbol")continue;let x=y.detail?.name;typeof x=="string"&&(p.has(x)||h.has(x)&&!b.has(x)&&`${x}`)}}catch{}for(let h of l)h.detail&&Object.freeze(h.detail),Object.freeze(h);g.parseDiagnostics=Object.freeze(l)}return g}finally{iS(this)}}appliedNonFunctions(n){let t=this.latexSyntax;if(!t)return[];let i=t.parse(n,{getSymbolType:o=>{let s=this.lookupDefinition(o);return s?fe(s)?s.operator.signature:ie(s)?s.value.type:Z.unknown:Z.unknown},...this._latexOptions}),r=new Set;return i!==null&&hN(i,r),Array.from(r).sort()}function(n,t,i){let{canonical:r,structural:o}=Pb(i);return Rb(this,n,t,{metadata:i?.metadata,canonical:r,structural:o,scope:i?.scope})}error(n,t){return l0(this,n,t)}typeError(n,t,i){return WO(this,n,t,i)}hold(n){return this._fn("Hold",[this.expr(n,{form:"raw"})])}tuple(...n){return new Sn(this,"Tuple",n.map(t=>typeof t=="number"?this.number(t):t.canonical),{canonical:!0})}type(n){return n instanceof Z?n:new Z(n,this._typeResolver)}string(n,t){return new ea(this,n,t)}symbol(n,t){return GO(this,this._commonSymbols,n,t)}number(n,t){return UO(this,this._commonNumbers,n,t)}rules(n,t){return kp(this,n,t)}getRuleSet(n){if(n??="standard-simplification",n==="standard-simplification"){this._simplificationRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("standard-simplification-rules");let t=this._cache("standard-simplification-rules",()=>{let r=kp(this,this._simplificationRules.rules,{canonical:!0}).rules.filter(o=>o.purpose!=="expand");return{rules:AA(r)}});return this._simplificationRules.markCached(),t}if(n==="solve-univariate"){this._solveRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("univariate-roots-rules");let t=this._cache("univariate-roots-rules",()=>kp(this,this._solveRules.rules));return this._solveRules.markCached(),t}if(n==="harmonization"){this._harmonizationRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("harmonization-rules");let t=this._cache("harmonization-rules",()=>kp(this,this._harmonizationRules.rules));return this._harmonizationRules.markCached(),t}}_fn(n,t,i){let r=i?.canonical??!0;return new Sn(this,n,t,{...i,canonical:r})}ask(n){return xS(this,n)}verify(n){return ES(this,n)}assume(n){return k6(this,n)}forget(n){vS(this,n)}};c0(()=>new yo);yo._latexSyntaxFactory=()=>new Ss;c0(()=>new yo({latexSyntax:new Ss}));globalThis[Symbol.for("io.cortexjs.compute-engine")]={ComputeEngine:yo.prototype.constructor,version:"0.86.1",LatexSyntax:Ss,LATEX_DICTIONARY:Aa,isExpression:Zd,isNumber:N,isSymbol:w,isFunction:m,isString:q,isTensor:Qt,isDictionary:Lt,isCollection:oy,isIndexedCollection:sy,numericValue:ze,sym:C};function bN(e){return e.fg===void 0&&e.bg===void 0&&(e.weight===void 0||e.weight==="normal")&&(e.italic===void 0||e.italic===!1)}var m0=class{width;indent;constructor(n){this.width=n?.width,this.indent=n?.indent??0}renderBlock(n){let t="spans"in n?this.renderSpans(n.spans):n.blocks.map(i=>this.renderBlock(i)).join(`
|
|
1582
|
+
${i}`:i:n.preamble,o=new sN(t,r);return{target:"interval-js",success:!0,code:t,calling:"expression",run:o}}var i0=class{_targets=new Map;register(n,t){k4(n),R4(t),this._targets.set(n,t)}get(n){return this._targets.get(n)}list(){return[...this._targets.keys()]}unregister(n){this._targets.delete(n)}registerDefaults(){this.register("javascript",new hc),this.register("glsl",new yc),this.register("wgsl",new yd),this.register("python",new Ec),this.register("interval-js",new _c)}};var r0=class{_listeners=[];_registered=new WeakSet;_pending=!1;_version=0;listen(n){return this._registered.has(n)||(this._registered.add(n),this._listeners.push(n)),()=>this._unsubscribe(n)}_unsubscribe(n){this._registered.has(n)&&(this._registered.delete(n),this._listeners=this._listeners.filter(t=>t!==n))}notify(){if(this._pending)return;this._pending=!0;let n=this._version+1;queueMicrotask(()=>{if(n!==this._version+1){this._pending=!1;return}this.notifyNow()})}notifyNow(){this._version++;for(let n of this._listeners)try{n?.onConfigurationChange?.()}catch(t){console.error("Listener error:",t)}this._pending=!1}};var o0=class{_generation=0;_mutationGeneration=0;_ephemeralWriteDepth=0;_tracker=new r0;get generation(){return this._generation}set generation(n){this._generation=n}get mutationGeneration(){return this._mutationGeneration}set mutationGeneration(n){this._mutationGeneration=n}get ephemeralWriteDepth(){return this._ephemeralWriteDepth}set ephemeralWriteDepth(n){this._ephemeralWriteDepth=n}reset(n){this._generation+=1,this._mutationGeneration+=1,n.refreshNumericConstants(),n.resetCommonSymbols(),n.purgeCaches(),this._tracker.notifyNow()}listen(n){return this._tracker.listen(n)}};function VW(e){return!!(e===void 0||e==="Number"||e===!0||Array.isArray(e)&&e.includes("Number"))}function GO(e,n,t,i){let r=i?.canonical??!0,o=i?.metadata,s=t.normalize(),a=s.toLowerCase();if(a==="infinity"||a==="+infinity")return e.PositiveInfinity;if(a==="-infinity")return e.NegativeInfinity;if(e.strict&&!yn(s))return e.error(["invalid-symbol",vi(s)],s);if(!r)return new hr(e,s,{metadata:o});if(e._isShadowedParameter(s)){let f=e._shadowedParameterType(s);if(f!==void 0){let d=e._shadowedParameterDef(s);if(d!==void 0)return new hr(e,s,{metadata:o,def:d});let g=e.context.lexicalScope;for(;g.noAutoDeclare&&g.parent;)g=g.parent;let h=g.bindings.get(s)??e._declareSymbolValue(s,{type:f,inferred:!1},g);return e._setShadowedParameterDef(s,h),new hr(e,s,{metadata:o,def:h})}let p=e.lookupDefinition(s);if(!p||ie(p)&&p.value.isConstant){let d=e.context.lexicalScope;for(;d.noAutoDeclare&&d.parent;)d=d.parent;p=e._declareSymbolValue(s,{type:"unknown",inferred:!0},d)}return new hr(e,s,{metadata:o,def:p})}let u=n[s];if(u)return u;let l=e.lookupDefinition(s);if(ie(l)&&l.value.holdUntil==="never")return l.value.value??e.Nothing;if(l)return new hr(e,s,{metadata:o,def:l});let c=e.context.lexicalScope;for(;c.noAutoDeclare&&c.parent;)c=c.parent;return l=e._declareSymbolValue(s,{type:"unknown",inferred:!0},c),new hr(e,s,{metadata:o,def:l})}function UO(e,n,t,i){let r=i?.metadata;if(!VW(i?.canonical)&&Mr(t))return e._fn("Rational",[e.number(t[0]),e.number(t[1])],{...r,canonical:!1});let s=Nh(e,t);if(r===void 0){if(typeof s=="number"){let a=s;if(a===1)return e.One;if(a===0)return e.Zero;if(a===-1)return e.NegativeOne;if(a===2)return e.Two;if(Number.isInteger(a)&&n[a]!==void 0)return n[a]??=new An(e,s),n[a];if(Number.isNaN(a))return e.NaN;if(!Number.isFinite(a))return a<0?e.NegativeInfinity:e.PositiveInfinity}else if(s instanceof je){if(s.isZero)return e.Zero;if(s.isOne)return e.One;if(s.isNegativeOne)return e.NegativeOne;if(s.isNaN)return e.NaN;if(s.isNegativeInfinity)return e.NegativeInfinity;if(s.isPositiveInfinity)return e.PositiveInfinity}}return new An(e,s,{metadata:r})}var Nc=class{_rules;_cachedLength=-1;constructor(n){this._rules=n}get rules(){return this._rules}set rules(n){this._rules=n,this._cachedLength=-1}hasMutatedSinceLastCache(){return this._cachedLength>=0&&this._rules.length!==this._cachedLength}markCached(){this._cachedLength=this._rules.length}};var s0=class{_precision;_angularUnit;_tolerance;_bignumTolerance;_negBignumTolerance;constructor(n){let t=n?.precision??iy;t==="machine"&&(t=Math.floor(Qi)),this._precision=t,S.precision=t,this._angularUnit=n?.angularUnit??"rad",this._tolerance=ku,this._bignumTolerance=new S(ku),this._negBignumTolerance=new S(-ku),this.setTolerance(n?.tolerance??"auto")}get precision(){return this._precision}setPrecision(n){let t=n;if(t==="machine"&&(t=Qi),t==="auto"&&(t=iy),t===this._precision)return!1;if(typeof t!="number"||t<=0)throw Error('Expected "machine" or a positive number');return this._precision=Math.max(t,Qi),S.precision=this._precision,this.setTolerance("auto"),!0}get angularUnit(){return this._angularUnit}setAngularUnit(n){if(n===this._angularUnit)return!1;if(typeof n!="string")throw Error("Expected a string");return this._angularUnit=n,!0}get tolerance(){return this._tolerance}setTolerance(n){let t=n;t==="auto"&&(t=ku),(!Number.isFinite(t)||t<0)&&(t=Math.pow(10,-this._precision+2)),this._tolerance=t,this._bignumTolerance=new S(t),this._negBignumTolerance=new S(-t)}get bignumTolerance(){return this._bignumTolerance}get negBignumTolerance(){return this._negBignumTolerance}get bignumNaN(){return S.NAN}get bignumZero(){return S.ZERO}get bignumOne(){return S.ONE}get bignumTwo(){return S.TWO}get bignumHalf(){return S.HALF}get bignumPi(){return S.PI}get bignumNegativeOne(){return S.NEGATIVE_ONE}bignum(n){if(n instanceof S)return n;try{return new S(n)}catch(t){t instanceof Error?console.error(t.message):console.error(String(t))}return S.NAN}};var a0=class{_timeLimit=2e3;_iterationLimit=1024;_recursionLimit=256;_recursionDepth=0;_maxCollectionSize=1e4;_deadline=void 0;_isVerifying=!1;get timeLimit(){return this._timeLimit}set timeLimit(n){this._timeLimit=n<=0?Number.POSITIVE_INFINITY:n}get iterationLimit(){return this._iterationLimit}set iterationLimit(n){this._iterationLimit=n<=0?Number.POSITIVE_INFINITY:n}get recursionLimit(){return this._recursionLimit}set recursionLimit(n){this._recursionLimit=n<=0?Number.POSITIVE_INFINITY:n}get recursionDepth(){return this._recursionDepth}enterRecursion(){if(this._recursionDepth>=this._recursionLimit)throw new Ae({cause:"recursion-depth-exceeded",message:"Recursion limit exceeded"});this._recursionDepth+=1}exitRecursion(){this._recursionDepth>0&&(this._recursionDepth-=1)}get maxCollectionSize(){return this._maxCollectionSize}set maxCollectionSize(n){this._maxCollectionSize=n<=0?Number.POSITIVE_INFINITY:n}get deadline(){return this._deadline}set deadline(n){this._deadline=n}get timeRemaining(){return this._deadline===void 0?Number.POSITIVE_INFINITY:this._deadline-Date.now()}get isVerifying(){return this._isVerifying}set isVerifying(n){this._isVerifying=n}shouldContinueExecution(){return this._deadline===void 0||this._deadline>=Date.now()}};function JW(e){if(typeof e!="string")return P4(e),e;let n=Mb.find(t=>t.name===e);if(!n)throw new Error(`Unknown standard library: "${e}"`);return n}function ZO(e){return e?Cb(e.map(JW)):[...kb()]}function HO(e,n){for(let t of n){let i=t.definitions;if(!i)continue;let r=Array.isArray(i)?i:[i];for(let o of r)g4(e,o)}}function Nd(e,n){let t=e[n];if(!t)throw new Error(`Common symbol "${n}" failed to initialize`);return t}var u0=class{constructor(n){this.engine=n}engine;initializeCommonNumbers(){return{Zero:new An(this.engine,0),One:new An(this.engine,1),Half:new An(this.engine,{rational:[1,2]}),NegativeOne:new An(this.engine,-1),Two:new An(this.engine,2),NaN:new An(this.engine,Number.NaN),PositiveInfinity:new An(this.engine,Number.POSITIVE_INFINITY),NegativeInfinity:new An(this.engine,Number.NEGATIVE_INFINITY),I:new An(this.engine,{im:1}),ComplexInfinity:new An(this.engine,{re:1/0,im:1/0})}}bootstrapLibraries(n){let t=ZO(n);HO(this.engine,t)}initializeCommonSymbolBindings(n){return G6(this.engine,n),{True:Nd(n,"True"),False:Nd(n,"False"),Pi:Nd(n,"Pi"),E:Nd(n,"ExponentialE"),Nothing:Nd(n,"Nothing")}}};function jW(e){let n=[],t=e;for(;t;)t.types&&n.push(...Object.keys(t.types)),t=t.parent;return n}function zW(e,n){let t=e;for(;t;){if(t.types?.[n])return t.types[n];t=t.parent}}function YO(e){return{get names(){return jW(e.context.lexicalScope)},resolve(n){return zW(e.context.lexicalScope,n)},forward(n){let t={kind:"reference",name:n,alias:!1,def:void 0};return e.context.lexicalScope.types??={},e.context.lexicalScope.types[n]=t,t}}}function l0(e,n,t){let i;typeof n=="string"?i=e.string(n):i=e.function("ErrorCode",n.map(s=>e.string(s)));let r;t&&mm(t)?r=e.function("LatexString",[e.string(ys(t))]):typeof t=="string"&&t.length>0&&(r=e.string(t));let o=[e.expr(i)];return r&&o.push(r),e.function("Error",o)}function WO(e,n,t,i){return t?l0(e,["incompatible-type",le(n),t.toString()],i):l0(e,["incompatible-type",le(n)],i)}var GW=null;function c0(e){GW=e}var UW=/^(Sin|Cos|Tan|Cot|Sec|Csc)$/;function f0(e){return UW.test(e.operator)?!0:m(e)?e.ops.some(f0):!1}function aa(e,...n){return n.includes(e.operator)?!0:m(e)?e.ops.some(t=>aa(t,...n)):!1}function Tn(e,n){let t=e.engine;if(m(e)&&e.ops.length>0){let i=e,r=i.ops.map(s=>Tn(s,n));r.some((s,a)=>s!==i.ops[a])&&(e=t._fn(i.operator,r))}return n(e)??e}function uN(e,n){if(!m(e)||!m(n))return!1;let t=e.op1,i=n.op1;return t!==void 0&&i!==void 0&&t.isSame(i)}function ZW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(i){if(t==="Sec")return n.One.div(n._fn("Cos",[i]));if(t==="Csc")return n.One.div(n._fn("Sin",[i]))}}function n7(e){return Tn(e,ZW)}function HW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(i){if(t==="Tan")return n._fn("Sin",[i]).div(n._fn("Cos",[i]));if(t==="Cot")return n._fn("Cos",[i]).div(n._fn("Sin",[i]))}}function t7(e){return Tn(e,HW)}function YW(e){let n=e.engine;if(e.operator!=="Divide"||!m(e))return;let t=e.op1,i=e.op2;if(!(!t||!i)){if(t.operator==="Sin"&&i.operator==="Cos"&&uN(t,i))return m(t)?n._fn("Tan",[t.op1]):void 0;if(t.operator==="Cos"&&i.operator==="Sin"&&uN(t,i))return m(t)?n._fn("Cot",[t.op1]):void 0}}function i7(e){return Tn(e,YW)}function WW(e){if(m(e,"Negate"))return e.op1;if(m(e,"Multiply")){let n=e.ops.findIndex(t=>t.isSame(-1));if(n>=0){let t=e.ops.filter((i,r)=>r!==n);return t.length===1?t[0]:e.engine._fn("Multiply",t)}}}function QW(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(!i)return;let r=WW(i);if(r){if(t==="Cos")return n._fn("Cos",[r]);if(t==="Sec")return n._fn("Sec",[r]);if(t==="Sin")return n._fn("Sin",[r]).neg();if(t==="Tan")return n._fn("Tan",[r]).neg();if(t==="Csc")return n._fn("Csc",[r]).neg();if(t==="Cot")return n._fn("Cot",[r]).neg()}}function r7(e){return Tn(e,QW)}function KW(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Sin"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.sub(n._fn("Cos",[r]).pow(2))}function lN(e){return Tn(e,KW)}function XW(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Cos"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.sub(n._fn("Sin",[r]).pow(2))}function o7(e){return Tn(e,XW)}function eQ(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||t.operator!=="Cos"||!i.isSame(2)||!m(t))return;let r=t.op1;if(r)return n.One.add(n._fn("Cos",[r.mul(2)])).div(2)}function s7(e){return Tn(e,eQ)}function nQ(e){let n=e.engine;if(m(e,"Divide")){let i=e.op1,r=e.op2;if(!i||!r||!r.isSame(2))return;if(m(i,"Add")&&i.ops.length===2)return QO(n,i.ops)}let t=i=>!!(i.re===.5&&i.im===0||i.isSame(n.Half));if(m(e,"Multiply")){let i=e.ops.findIndex(r=>t(r));if(i>=0){let r=e.ops.filter((o,s)=>s!==i);if(r.length===1&&r[0].operator==="Add"){let o=r[0];if(m(o)&&o.ops.length===2)return QO(n,o.ops)}}}if(m(e,"Add")&&e.ops.length===2){let i,r,o=!1,s=a=>a.re===-.5&&a.im===0;for(let a of e.ops){if(t(a)){i=a;continue}let u=a,l=!1;if(m(a,"Negate")&&(l=!0,u=a.op1),m(u,"Divide")&&u.op2?.isSame(2)){let c=u.op1;if(c?.operator==="Cos"){r=c,o=l;continue}}if(m(u,"Multiply")){let c=u.ops.findIndex(p=>t(p));if(c>=0){let p=u.ops.filter((d,g)=>g!==c);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=l;continue}}let f=u.ops.findIndex(p=>s(p));if(f>=0){let p=u.ops.filter((d,g)=>g!==f);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=!l;continue}}}}if(i&&r){if(!m(r))return;let a=r.op1;if(!a)return;let u;if(m(a,"Multiply")){let l=a.ops.findIndex(c=>c.isSame(2));if(l>=0){let c=a.ops.filter((f,p)=>p!==l);u=c.length===1?c[0]:n._fn("Multiply",c)}}return u?o?n._fn("Sin",[u]).pow(2):n._fn("Cos",[u]).pow(2):void 0}}}function QO(e,n){let t=-1,i=-1,r=!1;for(let u=0;u<n.length;u++)if(n[u].isSame(1))t=u;else if(n[u].operator==="Cos")i=u,r=!1;else if(n[u].operator==="Negate"){let l=n[u];m(l)&&l.op1?.operator==="Cos"&&(i=u,r=!0)}if(t<0||i<0)return;let o;if(r){let u=n[i];if(!m(u))return;o=u.op1}else o=n[i];if(!m(o))return;let s=o.op1;if(!s)return;let a;if(m(s,"Multiply")){let u=s.ops.findIndex(l=>l.isSame(2));if(u>=0){let l=s.ops.filter((c,f)=>f!==u);a=l.length===1?l[0]:e._fn("Multiply",l)}}if(a)return r?e._fn("Sin",[a]).pow(2):e._fn("Cos",[a]).pow(2)}function cN(e){return Tn(e,nQ)}function tQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r];if(!m(o)||!m(s))continue;let a=o.op1,u=s.op1;if(!a||!u)continue;let l;if(o.operator==="Sin"&&s.operator==="Cos"?l=n._fn("Sin",[a.add(u)]).add(n._fn("Sin",[a.sub(u)])).div(2):o.operator==="Cos"&&s.operator==="Sin"?l=n._fn("Sin",[a.add(u)]).sub(n._fn("Sin",[a.sub(u)])).div(2):o.operator==="Cos"&&s.operator==="Cos"?l=n._fn("Cos",[a.add(u)]).add(n._fn("Cos",[a.sub(u)])).div(2):o.operator==="Sin"&&s.operator==="Sin"&&(l=n._fn("Cos",[a.sub(u)]).sub(n._fn("Cos",[a.add(u)])).div(2)),l){let c=t.filter((f,p)=>p!==i&&p!==r);return c.length===0?l:l.mul(c.length===1?c[0]:n._fn("Multiply",c))}}}function a7(e){return Tn(e,tQ)}function iQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r],a;if(o.operator==="Sin"&&s.operator==="Sin"){if(!m(o)||!m(s))continue;let u=o.op1,l=s.op1;if(u&&l){let c=u.add(l).div(2),f=u.sub(l).div(2);a=n._fn("Sin",[c]).mul(n._fn("Cos",[f])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Cos"){if(!m(o)||!m(s))continue;let u=o.op1,l=s.op1;if(u&&l){let c=u.add(l).div(2),f=u.sub(l).div(2);a=n._fn("Cos",[c]).mul(n._fn("Cos",[f])).mul(2)}}else if(o.operator==="Sin"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Sin")continue;let u=s.op1;if(!m(u))continue;let l=o.op1,c=u.op1;if(l&&c){let f=l.add(c).div(2),p=l.sub(c).div(2);a=n._fn("Cos",[f]).mul(n._fn("Sin",[p])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Cos")continue;let u=s.op1;if(!m(u))continue;let l=o.op1,c=u.op1;if(l&&c){let f=l.add(c).div(2),p=l.sub(c).div(2);a=n._fn("Sin",[f]).mul(n._fn("Sin",[p])).mul(-2)}}if(a){let u=t.filter((l,c)=>c!==i&&c!==r);return u.length===0?a:a.add(u.length===1?u[0]:n._fn("Add",u))}}}function p0(e){return Tn(e,iQ)}function rQ(e){let n=e.engine,t=e.operator;if(t!=="Sin"&&t!=="Cos"||!m(e))return;let i=e.op1;if(i){if(m(i,"Add")&&i.ops.length===2){let[r,o]=i.ops;return t==="Sin"?n._fn("Sin",[r]).mul(n._fn("Cos",[o])).add(n._fn("Cos",[r]).mul(n._fn("Sin",[o]))):n._fn("Cos",[r]).mul(n._fn("Cos",[o])).sub(n._fn("Sin",[r]).mul(n._fn("Sin",[o])))}if(m(i,"Subtract")){let r=i.op1,o=i.op2;return!r||!o?void 0:t==="Sin"?n._fn("Sin",[r]).mul(n._fn("Cos",[o])).sub(n._fn("Cos",[r]).mul(n._fn("Sin",[o]))):n._fn("Cos",[r]).mul(n._fn("Cos",[o])).add(n._fn("Sin",[r]).mul(n._fn("Sin",[o])))}}}function u7(e){return Tn(e,rQ)}function oQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r],a=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Sin"&&k.operator==="Cos"?{sin:T,cos:k}:T.operator==="Cos"&&k.operator==="Sin"?{sin:k,cos:T}:null},u=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Cos"&&k.operator==="Cos"?{cos1:T,cos2:k}:null},l=_=>{if(_.operator!=="Multiply"||!m(_))return null;let I=_.ops;if(I.length!==2)return null;let[T,k]=I;return T.operator==="Sin"&&k.operator==="Sin"?{sin1:T,sin2:k}:null},c=_=>m(_)?_.op1:void 0,f=a(o),p=a(s),d=m(o,"Negate")&&o.op1?a(o.op1):null,g=m(s,"Negate")&&s.op1?a(s.op1):null;if(f&&p){let _=c(f.sin),I=c(f.cos),T=c(p.sin),k=c(p.cos);if(_&&I&&T&&k&&_.isSame(k)&&I.isSame(T)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(f&&g){let _=c(f.sin),I=c(f.cos),T=c(g.sin),k=c(g.cos);if(_&&I&&T&&k&&_.isSame(k)&&I.isSame(T)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(d&&p){let _=c(d.sin),I=c(d.cos),T=c(p.sin),k=c(p.cos);if(_&&I&&T&&k&&T.isSame(I)&&k.isSame(_)){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Sin",[T.sub(k)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}let h=u(o),b=u(s),y=l(o),x=l(s),E=m(o,"Negate")&&o.op1?l(o.op1):null,v=m(s,"Negate")&&s.op1?l(s.op1):null;if(h&&v){let _=c(h.cos1),I=c(h.cos2),T=c(v.sin1),k=c(v.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(E&&b){let _=c(b.cos1),I=c(b.cos2),T=c(E.sin1),k=c(E.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.add(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(h&&x){let _=c(h.cos1),I=c(h.cos2),T=c(x.sin1),k=c(x.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}if(y&&b){let _=c(b.cos1),I=c(b.cos2),T=c(y.sin1),k=c(y.sin2);if(_&&I&&T&&k&&(_.isSame(T)&&I.isSame(k)||_.isSame(k)&&I.isSame(T))){let A=t.filter((B,O)=>O!==i&&O!==r),P=n._fn("Cos",[_.sub(I)]);return A.length===0?P:P.add(A.length===1?A[0]:n._fn("Add",A))}}}}function d0(e){return Tn(e,oQ)}function sQ(e){let n=e.engine,t=e.operator;if(t!=="Sin"&&t!=="Cos"||!m(e))return;let i=e.op1;if(i&&m(i,"Multiply")){let r=i.ops,o=r.findIndex(s=>s.isSame(2));if(o>=0){let s=r.filter((u,l)=>l!==o),a=s.length===1?s[0]:n._fn("Multiply",s);return t==="Sin"?n._fn("Sin",[a]).mul(n._fn("Cos",[a])).mul(2):n._fn("Cos",[a]).pow(2).mul(2).sub(n.One)}}}function fN(e){return Tn(e,sQ)}function aQ(e){let n=e.engine;if(m(e,"Multiply")){let t=e.ops,i=t.findIndex(r=>r.isSame(2));if(i>=0){let r=t.filter((a,u)=>u!==i),o,s;for(let a of r)a.operator==="Sin"&&!o?o=a:a.operator==="Cos"&&!s&&(s=a);if(o&&s&&uN(o,s)){if(!m(o))return;let a=r.filter(l=>l!==o&&l!==s),u=n._fn("Sin",[o.op1.mul(2)]);return a.length===0?u:u.mul(a.length===1?a[0]:n._fn("Multiply",a))}}}if(m(e,"Add")&&e.ops.length===2){let[t,i]=e.ops;if(m(t,"Power")&&t.op1?.operator==="Cos"&&t.op2?.isSame(2)&&i.operator==="Negate"&&m(i)&&i.op1?.operator==="Power"&&m(i.op1)&&i.op1.op1?.operator==="Sin"&&i.op1.op2?.isSame(2)){let u=t.op1,l=i.op1;if(m(u)&&m(l)){let c=l.op1;if(m(c)){let f=u.op1,p=c.op1;if(f&&p&&f.isSame(p))return n._fn("Cos",[f.mul(2)])}}}let r=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Cos"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}},o=r(t);if(o&&(i.isSame(-1)||m(i,"Negate")&&i.op1?.isSame(1)))return n._fn("Cos",[o.mul(2)]);if(o=r(i),o&&(t.isSame(-1)||m(t,"Negate")&&t.op1?.isSame(1)))return n._fn("Cos",[o.mul(2)]);let s=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Sin"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}};if(t.isSame(1)&&m(i,"Negate")&&i.op1){let u=s(i.op1);if(u)return n._fn("Cos",[u.mul(2)])}if(i.isSame(1)&&m(t,"Negate")&&t.op1){let u=s(t.op1);if(u)return n._fn("Cos",[u.mul(2)])}let a=u=>{if(!m(u,"Multiply"))return;let l=u.ops.findIndex(p=>p.isSame(-2));if(l<0)return;let c=u.ops.filter((p,d)=>d!==l);if(c.length!==1)return;let f=c[0];if(m(f,"Power")&&f.op1?.operator==="Sin"&&f.op2?.isSame(2)){let p=f.op1;if(m(p))return p.op1}};if(t.isSame(1)){let u=a(i);if(u)return n._fn("Cos",[u.mul(2)])}if(i.isSame(1)){let u=a(t);if(u)return n._fn("Cos",[u.mul(2)])}}}function l7(e){return Tn(e,aQ)}function KO(e){let n=!1,t=e;if(m(t,"Negate")&&t.op1)n=!0,t=t.op1;else if(m(t,"Multiply")&&t.ops.length===2){let s=t.ops.findIndex(a=>a.isSame(-1));s>=0&&(n=!0,t=t.ops[1-s])}if(!m(t,"Power"))return;let i=t.op1,r=t.op2;if(!i||!r||!(r.isSame(2)||r.isSame(4))||i.operator!=="Sin"&&i.operator!=="Cos"||!m(i))return;let o=i.op1;if(o)return{func:i.operator,arg:o,power:r.isSame(2)?2:4,negated:n}}function uQ(e){let n=e.engine;if(!m(e,"Add")||e.ops.length!==2)return;let t=KO(e.ops[0]),i=KO(e.ops[1]);if(!t||!i||t.negated===i.negated||t.func===i.func||t.power!==i.power||!t.arg.isSame(i.arg))return;let r=t.negated?i:t,o=n._fn("Cos",[r.arg.mul(2)]);return r.func==="Cos"?o:o.neg()}function c7(e){return Tn(e,uQ)}function lQ(e){let n=e.engine;if(e.operator!=="Tan"||!m(e))return;let t=e.op1;if(t){if(m(t,"Add")&&t.ops.length===2){let[i,r]=t.ops,o=n._fn("Tan",[i]),s=n._fn("Tan",[r]);return o.add(s).div(n.One.sub(o.mul(s)))}if(m(t,"Subtract")){let i=t.op1,r=t.op2;if(!i||!r)return;let o=n._fn("Tan",[i]),s=n._fn("Tan",[r]);return o.sub(s).div(n.One.add(o.mul(s)))}}}function f7(e){return Tn(e,lQ)}var cQ=[{value:0,angle:[0,1]},{value:1/Math.sqrt(3),angle:[1,6]},{value:1,angle:[1,4]},{value:Math.sqrt(3),angle:[1,3]},{value:2-Math.sqrt(3),angle:[1,12]},{value:2+Math.sqrt(3),angle:[5,12]}];function fQ(e,n=1e-10){for(let t of cQ)if(Math.abs(t.value-e)<n)return t.angle}function pQ(e){if(e.operator!=="Multiply"||!m(e))return;let n=e.ops;if(n.length<2)return;let t=[],i=1;for(let r of n)if(m(r,"Tan")&&r.op1)t.push(r.op1);else if(m(r,"Negate")&&r.op1?.operator==="Sqrt"){let o=r.op1;if(m(o)){let s=o.op1;if(N(s)&&typeof s.re=="number")i*=-Math.sqrt(s.re);else return}else return}else if(m(r,"Sqrt")){let o=r.op1;if(o&&N(o)&&typeof o.re=="number")i*=Math.sqrt(o.re);else return}else if(N(r)&&typeof r.re=="number")i*=r.re;else return;if(t.length===2)return[i,t[0],t[1]]}function XO(e){if(m(e,"Multiply")){let n=!1,t;for(let i of e.ops)if(w(i,"Pi"))n=!0;else if(N(i)&&typeof i.re=="number"){let r=i.re;for(let o=1;o<=36;o++){let s=Math.round(r*o);if(Math.abs(s/o-r)<1e-10){t=[s,o];break}}}if(n&&t)return t}if(w(e,"Pi"))return[1,1]}function dQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length!==3)return;let i=[],r;for(let x=0;x<t.length;x++){let E=t[x];if(m(E,"Tan")&&E.op1)i.push({arg:E.op1,index:x});else{let v=pQ(E);v&&(r={coef:v[0],arg1:v[1],arg2:v[2],index:x})}}if(i.length!==2||!r)return;let[o,s]=i,a=o.arg.isSame(r.arg1)||o.arg.isSame(r.arg2),u=s.arg.isSame(r.arg1)||s.arg.isSame(r.arg2),l=o.arg.isSame(r.arg2)||o.arg.isSame(r.arg1),c=s.arg.isSame(r.arg2)||s.arg.isSame(r.arg1);if(!(a&&c||u&&l))return;let f=-r.coef;if(f<=0)return;let p=fQ(f);if(!p)return;let d=XO(o.arg),g=XO(s.arg);if(!d||!g)return;let h=e7(e7(d[1],g[1]),p[1]);if(d[0]*(h/d[1])+g[0]*(h/g[1])+p[0]*(h/p[1])!==h)return;let y=n._fn("Multiply",[n.number([p[0],p[1]]),n.symbol("Pi")]);return n._fn("Tan",[y]).neg()}function e7(e,n){return Math.abs(e*n)/mQ(e,n)}function mQ(e,n){for(e=Math.abs(e),n=Math.abs(n);n;){let t=n;n=e%n,e=t}return e}function p7(e){return Tn(e,dQ)}function gQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(!(t.length<2))for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let o=t[i],s=t[r];if(!m(o)||!m(s))continue;let a=o.op1,u=s.op1;if(!(!a||!u)){if(o.operator==="Tan"&&s.operator==="Tan"){let l=o,c=s,f=n._fn("Cot",[a.add(u)]),p=n.One.sub(l.add(c).mul(f)),d=t.filter((g,h)=>h!==i&&h!==r);return d.length===0?p:p.mul(d.length===1?d[0]:n._fn("Multiply",d))}if(o.operator==="Cot"&&s.operator==="Cot"){let l=o,c=s,f=n._fn("Cot",[a.add(u)]),p=n.One.add(l.add(c).mul(f)),d=t.filter((g,h)=>h!==i&&h!==r);return d.length===0?p:p.mul(d.length===1?d[0]:n._fn("Multiply",d))}}}}function d7(e){return Tn(e,gQ)}function hQ(e){let n=e.engine;if(e.operator!=="Power"||!m(e))return;let t=e.op1,i=e.op2;if(!t||!i||!i.isSame(2)||!m(t))return;let r=t.op1;if(r){if(t.operator==="Tan")return n._fn("Sec",[r]).pow(2).sub(n.One);if(t.operator==="Cot")return n._fn("Csc",[r]).pow(2).sub(n.One);if(t.operator==="Sec")return n.One.add(n._fn("Tan",[r]).pow(2));if(t.operator==="Csc")return n.One.add(n._fn("Cot",[r]).pow(2))}}function m7(e){return Tn(e,hQ)}function bQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length!==2)return;let i=p=>{let d=!1,g=p;if(m(p,"Negate")&&(d=!0,g=p.op1),!m(g)||g.operator!=="Power"||!g.op2?.isSame(2))return null;let h=g.op1;if(!m(h)||!h.op1)return null;let b=h.operator;return["Tan","Cot","Sec","Csc"].includes(b)?{func:b,arg:h.op1,neg:d}:null},r=i(t[0]),o=i(t[1]);if(r&&o&&r.arg.isSame(o.arg)){if(r.func==="Cot"&&!r.neg&&o.func==="Csc"&&o.neg||r.func==="Csc"&&r.neg&&o.func==="Cot"&&!o.neg)return n.number(-1);if(r.func==="Csc"&&!r.neg&&o.func==="Cot"&&o.neg||r.func==="Cot"&&r.neg&&o.func==="Csc"&&!o.neg)return n.One;if(r.func==="Tan"&&!r.neg&&o.func==="Sec"&&o.neg||r.func==="Sec"&&r.neg&&o.func==="Tan"&&!o.neg)return n.number(-1);if(r.func==="Sec"&&!r.neg&&o.func==="Tan"&&o.neg||r.func==="Tan"&&r.neg&&o.func==="Sec"&&!o.neg)return n.One}let s=-1,a=-1,u=!1;for(let p=0;p<t.length;p++){let d=t[p];d.isSame(1)?(s=p,u=!1):d.isSame(-1)||m(d,"Negate")&&d.op1?.isSame(1)?(s=p,u=!0):m(d,"Power")&&d.op2?.isSame(2)&&(a=p)}if(s<0||a<0)return;let l=t[a];if(!m(l))return;let c=l.op1;if(!c||!m(c))return;let f=c.op1;if(f){if(c.operator==="Sec"&&u)return n._fn("Tan",[f]).pow(2);if(c.operator==="Csc"&&u)return n._fn("Cot",[f]).pow(2);if(c.operator==="Tan"&&!u)return n._fn("Sec",[f]).pow(2);if(c.operator==="Cot"&&!u)return n._fn("Csc",[f]).pow(2)}}function pN(e){return Tn(e,bQ)}function yQ(e){let n=e.engine;if(!m(e,"Multiply"))return[1,n.One,e];for(let t=0;t<e.ops.length;t++){let i=e.ops[t],r;if(N(i)&&typeof i.re=="number"&&i.im===0&&(r=i.re),r!==void 0){let o=e.ops.filter((a,u)=>u!==t),s=o.length===1?o[0]:n._fn("Multiply",o);return[r,i,s]}}return[1,n.One,e]}function xQ(e){let n=e.engine;if(e.operator!=="Multiply"||!m(e))return;let t=e.ops;if(t.length<2)return;let i=[],r=[];for(let T of t)if(m(T,"Cos")&&T.op1){let k=yQ(T.op1);k?i.push({arg:k[2],numericMult:k[0],symbolicCoeff:k[1]}):i.push({arg:T.op1,numericMult:1,symbolicCoeff:n.One})}else r.push(T);if(i.length<2)return;let o=i[0].arg,s=i.filter(T=>T.arg.isSame(o)),a=i.filter(T=>!T.arg.isSame(o));if(s.length<2)return;s.sort((T,k)=>T.numericMult-k.numericMult);let u=[],l=[],c=[...s],f=c[0].numericMult;if(f>0){u.push(c[0]);let T=new Set([0]),k=f*2;for(;;){let A=c.findIndex((P,B)=>!T.has(B)&&Math.abs(P.numericMult-k)<1e-10);if(A===-1)break;u.push(c[A]),T.add(A),k*=2}l=c.filter((A,P)=>!T.has(P))}if(u.length<2)return;let p=u[0].numericMult,d=[...r];for(let T of l){let k=T.symbolicCoeff.isSame(n.One)?T.arg:n._fn("Multiply",[T.symbolicCoeff,T.arg]);d.push(n._fn("Cos",[k]))}for(let T of a){let k=T.symbolicCoeff.isSame(n.One)?T.arg:n._fn("Multiply",[T.symbolicCoeff,T.arg]);d.push(n._fn("Cos",[k]))}let g=u.length,h=u[0].symbolicCoeff,b=Math.pow(2,g);if(w(o,"Pi")){let T=1/(b+1);if(Math.abs(p-T)<1e-10){let k=n.number([1,b]);return d.length===0?k:k.mul(d.length===1?d[0]:n._fn("Multiply",d))}}let y=h.mul(b),x=h.isSame(n.One)?o:n._fn("Multiply",[h,o]),E=n._fn("Multiply",[y,o]),v=n._fn("Sin",[E]),_=n._fn("Sin",[x]),I=v.div(n.number(b).mul(_));return d.length===0?I:I.mul(d.length===1?d[0]:n._fn("Multiply",d))}function g7(e){return Tn(e,xQ)}function EQ(e){if(m(e,"Power")&&e.op2?.isSame(2)){let n=e.op1;if(m(n,"Sin")&&n.op1)return{func:"Sin",arg:n.op1,coef:1};if(m(n,"Cos")&&n.op1)return{func:"Cos",arg:n.op1,coef:1}}if(m(e,"Multiply")){let n=1,t;for(let i of e.ops)if(m(i,"Power")&&i.op2?.isSame(2)){let r=i.op1;(r?.operator==="Sin"||r?.operator==="Cos")&&(t=i)}else typeof i.re=="number"&&i.im===0&&(n*=i.re);if(m(t)){let i=t.op1;if(m(i,"Sin")&&i.op1)return{func:"Sin",arg:i.op1,coef:n};if(m(i,"Cos")&&i.op1)return{func:"Cos",arg:i.op1,coef:n}}}return null}function vQ(e){let n=e.engine;if(e.operator!=="Add"||!m(e))return;let t=e.ops;if(t.length<2)return;let i=[],r=[],o=[];for(let s=0;s<t.length;s++){let a=t[s],u=EQ(a);u?i.push({...u,index:s}):typeof a.re=="number"&&a.im===0&&N(a)?o.push({value:a.re,index:s}):r.push({expr:a,index:s})}for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let u=i[s],l=i[a];if(u.arg.isSame(l.arg)&&(u.func==="Sin"&&l.func==="Cos"||u.func==="Cos"&&l.func==="Sin")&&Math.abs(u.coef-l.coef)<1e-10){let c=u.coef,f=new Set([u.index,l.index]),p=t.filter((d,g)=>!f.has(g));return p.length===0?n.number(c):c===1?n._fn("Add",[n.One,...p]):n._fn("Add",[n.number(c),...p])}}for(let s of i)if(s.coef<0){let a=Math.abs(s.coef);for(let u of o)if(Math.abs(u.value-a)<1e-10){let l=new Set([s.index,u.index]),c=t.filter((d,g)=>!l.has(g)),f=s.func==="Sin"?"Cos":"Sin",p=n._fn(f,[s.arg]).pow(2).mul(a);return c.length===0?p:n._fn("Add",[p,...c])}}}function h7(e){return Tn(e,vQ)}var SQ=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]);function dN(e){let n=0;if(SQ.has(e.operator)&&(n=1),m(e))for(let t of e.ops)n+=dN(t);return n}function mN(e){if(w(e)||N(e))return 1;let n=1;if(m(e))for(let t of e.ops)n+=mN(t);return n}function b7(e){let n=dN(e),t=mN(e);return n*1e3+t}var y7=b7;function gN(e,n){if(e.length===0)throw new Error("bestOf called with empty array");if(e.length===1)return e[0];let t=e[0],i=n(t);for(let r=1;r<e.length;r++){let o=n(e[r]);o<i&&(t=e[r],i=o)}return t}function wd(e,n){let t=n(e);return t.isSame(e)?null:t}function x7(e,n){let t=wd(e,lN),i=wd(e,o7),r=[e];return t&&r.push(t),i&&r.push(i),gN(r,n)}function _Q(e,n){return x7(e,n)}function NQ(e,n){let t=wd(e,a7),i=[e];if(t){i.push(t);let r=wd(t,d0);r&&i.push(r)}return gN(i,n)}function wQ(e,n){let t=wd(e,d0),i=[e];return t&&i.push(t),gN(i,n)}function IQ(e,n){let t=f7(e);return t=d7(t),t}function TQ(e,n){let t=e;return t=u7(t),t=fN(t),t=lN(t),t=s7(t),t=fN(t),t=NQ(t,n),t=x7(t,n),t=p0(t),t=_Q(t,n),t=p0(t),t=wQ(t,n),t}function E7(e,n){if(!f0(e))return;let t=n?.measure??y7,i=n?.maxIterations??100,r=e,o=0,s=e,a=t(e),u=_=>{let I=t(_);I<a&&(s=_,a=I)};r=r7(r),u(r);let l=pN(r);u(l);let c=m7(r);u(c),r=s;let f=cN(r);if(u(f),r=s,aa(r,"Sec","Csc")&&(r=n7(r),s=r,a=t(r)),aa(r,"Tan","Cot")){let _=IQ(r,t);u(_),r=_}if(aa(r,"Tan","Cot")&&(r=t7(r),u(r)),aa(r,"Sin","Cos")){let _=p0(r);u(_),r=s}if(aa(r,"Sin","Cos")){let _=t(r);for(;o<i;){o++;let I=TQ(r,t),T=t(I);if(u(I),T>=_)break;r=I,_=T}}let p=i7(s);u(p);let d=l7(s);u(d);let g=c7(s);u(g);let h=g7(s);u(h);let b=cN(s);u(b);let y=pN(s);u(y);let x=d0(s);u(x);let E=h7(s);u(E);let v=p7(s);if(u(v),s.operator==="Add"||s.operator==="Multiply"){let _=e.engine.expr(s.json);u(_)}if(!s.isSame(e))return{value:s,because:"fu"}}function hN(e,n){if(Array.isArray(e)){if(e[0]==="InvisibleOperator")for(let t=1;t+1<e.length;t++){let i=e[t],r=e[t+1];typeof i=="string"&&Array.isArray(r)&&r[0]==="Delimiter"&&n.add(i)}for(let t of e)hN(t,n);return}e!==null&&typeof e=="object"&&"fn"in e&&Array.isArray(e.fn)&&hN(e.fn,n)}var yo=class e{static _latexSyntaxFactory=null;True;False;Pi;E;Nothing;Zero;One;Half;NegativeOne;Two;I;NaN;PositiveInfinity;NegativeInfinity;ComplexInfinity;_numericConfiguration;_cacheStore=new $b;_runtimeState=new a0;_configurationLifecycle=new o0;_cost;_randomSeed=null;_rng;_integrationProvider;_simplificationRules=new Nc([...e6]);_solveRules=new Nc([...nR]);_harmonizationRules=new Nc([...oR]);_compilationTargets=new i0;_fuAlgorithm=E7;_commonSymbols={Pi:null,True:null,False:null,All:null,Nothing:null,None:null,Undefined:null,ImaginaryUnit:null,ExponentialE:null};_commonNumbers={"-5":null,"-4":null,"-3":null,"-2":null,2:null,3:null,4:null,5:null,6:null,7:null,8:null,9:null,10:null,11:null,12:null,36:null};_evalContextStack=[];get context(){return this._evalContextStack[this._evalContextStack.length-1]}get contextStack(){return[...this._evalContextStack]}set contextStack(n){this._evalContextStack=[...n]}__typeResolver;get _typeResolver(){return this.__typeResolver??=YO(this),this.__typeResolver}declareType(n,t,i){f6(this,n,t,i)}get trace(){return this._evalContextStack.map(n=>n.name).filter(n=>n!==void 0).reverse()}get _generation(){return this._configurationLifecycle.generation}set _generation(n){this._configurationLifecycle.generation=n}get _mutationGeneration(){return this._configurationLifecycle.mutationGeneration}set _mutationGeneration(n){this._configurationLifecycle.mutationGeneration=n}get _ephemeralWriteDepth(){return this._configurationLifecycle.ephemeralWriteDepth}set _ephemeralWriteDepth(n){this._configurationLifecycle.ephemeralWriteDepth=n}_inferenceTxDepth=0;_freshlyInferred=null;strict;static getStandardLibrary(n){return kb(n)}constructor(n){if(n!==void 0&&typeof n!="object")throw Error("Unexpected argument");this.strict=!0,this._numericConfiguration=new s0({precision:n?.precision,tolerance:n?.tolerance??"auto",angularUnit:"rad"});let t=new u0(this),i=t.initializeCommonNumbers();this.Zero=i.Zero,this.One=i.One,this.Half=i.Half,this.NegativeOne=i.NegativeOne,this.Two=i.Two,this.NaN=i.NaN,this.PositiveInfinity=i.PositiveInfinity,this.NegativeInfinity=i.NegativeInfinity,this.I=i.I,this.ComplexInfinity=i.ComplexInfinity,this._reset(),this.pushScope(void 0,"system"),this.declareType("limits","expression<Limits>"),this.declareType("distribution","expression<NormalDistribution> | expression<BinomialDistribution> | expression<PoissonDistribution> | expression<UniformDistribution> | expression<ExponentialDistribution>",{alias:!0}),t.bootstrapLibraries(n?.libraries);let r=t.initializeCommonSymbolBindings(this._commonSymbols);this.True=r.True,this.False=r.False,this.Pi=r.Pi,this.E=r.E,this.Nothing=r.Nothing,this.pushScope(void 0,"global"),this._compilationTargets.registerDefaults(),n?.latexSyntax&&(this._latexSyntax=n.latexSyntax),n?.latexOptions&&(this._latexOptions={...n.latexOptions}),Ew(this)}toJSON(){return"[ComputeEngine]"}[Symbol.toStringTag]="ComputeEngine";_reset(){this._configurationLifecycle.reset({refreshNumericConstants:()=>{},resetCommonSymbols:()=>U6(this._commonSymbols),purgeCaches:()=>this._cacheStore.purgeValues()})}listenToConfigurationChange(n){return this._configurationLifecycle.listen(n)}_compile(n,t){return dd(n,t)}getCompilationTarget(n){return this._compilationTargets.get(n)}listCompilationTargets(){return this._compilationTargets.list()}registerCompilationTarget(n,t){this._compilationTargets.register(n,t)}unregisterCompilationTarget(n){this._compilationTargets.unregister(n)}get precision(){return this._numericConfiguration.precision}set precision(n){this._numericConfiguration.setPrecision(n)&&this._reset()}get angularUnit(){return this._numericConfiguration.angularUnit}set angularUnit(n){this._numericConfiguration.setAngularUnit(n)&&this._reset()}get timeLimit(){return this._runtimeState.timeLimit}set timeLimit(n){this._runtimeState.timeLimit=n}withTimeLimit(n,t){let i=this._runtimeState.deadline,r=Date.now()+n;this._runtimeState.deadline=i===void 0?r:Math.min(i,r);try{return t()}finally{this._runtimeState.deadline=i}}get deadline(){return this._runtimeState.deadline}set deadline(n){this._runtimeState.deadline=n}get _deadline(){return this._runtimeState.deadline}set _deadline(n){this._runtimeState.deadline=n}get _timeRemaining(){return this._runtimeState.timeRemaining}get iterationLimit(){return this._runtimeState.iterationLimit}set iterationLimit(n){this._runtimeState.iterationLimit=n}get recursionLimit(){return this._runtimeState.recursionLimit}set recursionLimit(n){this._runtimeState.recursionLimit=n}_enterRecursion(){this._runtimeState.enterRecursion()}_exitRecursion(){this._runtimeState.exitRecursion()}get maxCollectionSize(){return this._runtimeState.maxCollectionSize}set maxCollectionSize(n){this._runtimeState.maxCollectionSize=n}get _isVerifying(){return this._runtimeState.isVerifying}set _isVerifying(n){this._runtimeState.isVerifying=n}get isVerifying(){return this._runtimeState.isVerifying}get tolerance(){return this._numericConfiguration.tolerance}set tolerance(n){this._numericConfiguration.setTolerance(n)}get randomSeed(){return this._randomSeed}set randomSeed(n){this._randomSeed=n,this._rng=n===null?void 0:dp(Zx(n))}_random(){return this._rng?this._rng():Math.random()}_randomNumericSeed(){return this._randomSeed===null?null:Zx(this._randomSeed)}chop(n){let t=this._numericConfiguration.tolerance;return typeof n=="number"?Math.abs(n)<=t?0:n:n instanceof S?n.isPositive()&&n.lte(this._numericConfiguration.bignumTolerance)||n.isNegative()&&n.gte(this._numericConfiguration.negBignumTolerance)||n.isZero()?0:n:n instanceof L&&Math.abs(n.re)<=t&&Math.abs(n.im)<=t?0:n}bignum(n){return this._numericConfiguration.bignum(n)}complex(n,t){return n instanceof S&&(n=n.toNumber()),t instanceof S&&(t=t.toNumber()),new L(n,t)}_numericValue(n){if(n instanceof je)return n.asExact??n;let t=this._numericConfiguration.precision>Qi?i=>new Ba(i):i=>new qo(i);if(typeof n=="number")return Number.isInteger(n)?new Ne(n,t):t(n);if(typeof n=="bigint")return new Ne(n,t);if(Mr(n))return new Ne({rational:n},t);if(n instanceof S){if(n.isInteger()){let i=ln(n.toString());if(i!==null)return new Ne(i,t)}return t(n)}if(n instanceof L)return n.im===0?this._numericValue(n.re):t({re:n.re,im:n.im});if("im"in n||"re"in n)return n.im!==void 0&&n.im!==0?t(n):n.re instanceof S&&n.re.isInteger()?new Ne({rational:[ln(n.re.toString()),BigInt(1)]},t):typeof n.re=="number"&&Number.isInteger(n.re)?new Ne({rational:[n.re,1]},t):t(n);if("radical"in n||"rational"in n){let i=n;if(i.radical!==void 0&&i.radical!==1){if(!Number.isInteger(i.radical)||i.radical<1)return t({re:Vu(i.rational??[1,1])*Math.sqrt(i.radical)});if(i.radical>=Se){let[r,o]=Di(i.radical,2);if(o>=Se)return t({re:Vu(i.rational??[1,1])*Math.sqrt(i.radical)});i={...i,radical:o,rational:Ue(i.rational??[1,1],[r,1])}}}return i.rational&&Wn(i.rational)&&(!Number.isInteger(i.rational[0])||!Number.isInteger(i.rational[1]))?t(i):new Ne(i,t)}throw Error(`Unexpected value: ${typeof n=="object"?JSON.stringify(n):String(n)}`)}get costFunction(){return this._cost??h4}set costFunction(n){this._cost=typeof n=="function"?n:void 0}get simplificationRules(){return this._simplificationRules.rules}set simplificationRules(n){this._simplificationRules.rules=n,this._cacheStore.invalidate("standard-simplification-rules")}get solveRules(){return this._solveRules.rules}set solveRules(n){this._solveRules.rules=n,this._cacheStore.invalidate("univariate-roots-rules")}get harmonizationRules(){return this._harmonizationRules.rules}set harmonizationRules(n){this._harmonizationRules.rules=n,this._cacheStore.invalidate("harmonization-rules")}lookupDefinition(n){return r6(this,n)}normalizeIdentifier(n){if(!n)return"";if(yn(n))return n;this.pushScope();try{let t=this.parse(n);if(w(t))return t.symbol}finally{this.popScope()}return""}operatorInfo(n){let t=this.lookupDefinition(n);if(!t||!fe(t))return;let i=t.operator,r=!!(i.evaluate||i.collection);return{kind:r?"function":"opaque",signature:i.signature,canEvaluate:r}}symbolInfo(n){let t=this.lookupDefinition(n);if(!t||!ie(t))return;let i=t.value;return{kind:i.isConstant?"constant":"variable",type:i.type}}searchDefinitions(n,t){return o6(this,n,t)}suggestOperatorName(n){return s6(this,n)}functionProperties(n){return nu(this,n)}_declareSymbolValue(n,t,i){return a6(this,n,t,i)}_declareSymbolOperator(n,t,i){return u6(this,n,t,i)}pushScope(n,t){b6(this,n,t)}popScope(){y6(this)}_pushEvalContext(n,t){dS(this,n,t)}_popEvalContext(){mS(this)}_inScope(n,t){return x6(this,n,t)}_printStack(n){E6(this,n)}_shadowedParameterStack=[];_pushShadowedParameters(n,t){this._shadowedParameterStack.push({names:new Set(n),types:t,defs:new Map})}_popShadowedParameters(){this._shadowedParameterStack.pop()}_isShadowedParameter(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return!0;return!1}_shadowedParameterType(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return t[i].types?.get(n)}_shadowedParameterDef(n){let t=this._shadowedParameterStack;for(let i=t.length-1;i>=0;i--)if(t[i].names.has(n))return t[i].defs.get(n)}_setShadowedParameterDef(n,t){let i=this._shadowedParameterStack;for(let r=i.length-1;r>=0;r--)if(i[r].names.has(n)){i[r].defs.set(n,t);return}}_getSymbolValue(n){return l6(this,n)}_setSymbolValue(n,t){c6(this,n,t)}declare(n,t,i){return p6(this,n,t,i)}declareSequence(n,t){return D6(this,n,t)}getSequenceStatus(n){return O6(this,n)}getSequence(n){return L6(this,n)}listSequences(){return F6(this)}isSequence(n){return B6(this,n)}clearSequenceCache(n){$6(this,n)}getSequenceCache(n){return q6(this,n)}getSequenceTerms(n,t,i,r){return V6(this,n,t,i,r)}lookupOEIS(n,t){return J6(this,n,t)}checkSequenceOEIS(n,t,i){return j6(this,n,t,i)}interpret(n,t){return z6(this,n,t)}assign(n,t){return d6(this,n,t)}_shouldContinueExecution(){return this._runtimeState.shouldContinueExecution()}_checkContinueExecution(){if(!this._shouldContinueExecution())throw new Error("timeout")}_cache(n,t,i){return this._cacheStore.getOrBuild(n,t,i)}expr(n,t){let{canonical:i,structural:r}=Pb(t);return Yt(this,n,{canonical:i,structural:r,scope:t?.scope})}box(n,t){return this.expr(n,t)}_latexSyntax;get latexSyntax(){return!this._latexSyntax&&e._latexSyntaxFactory&&(this._latexSyntax=e._latexSyntaxFactory()),this._latexSyntax}_requireLatexSyntax(){if(!this._latexSyntax&&e._latexSyntaxFactory&&(this._latexSyntax=e._latexSyntaxFactory()),!this._latexSyntax)throw new Error("LatexSyntax not available. Pass a LatexSyntax instance to the ComputeEngine constructor.");return this._latexSyntax}_latexOptions={};get latexOptions(){return this._latexOptions}set latexOptions(n){this._latexOptions={...n}}parse(n,t){if(n==null)return null;if(typeof n!="string")throw Error("ce.parse(): expected a LaTeX string");let i=this._requireLatexSyntax(),{form:r,canonical:o,structural:s,...a}=t??{},u=a.diagnostics??this._latexOptions?.diagnostics??!1,l,c,f,p=new Set;if(u){l=[],f=g=>p.add(g);let d=new Set;c=g=>{let h=`${g.code} ${g.start} ${g.end} ${g.detail?JSON.stringify(g.detail):""}`;d.has(h)||(d.add(h),l.push(g))}}tS(this);try{let d=i.parse(n,{getSymbolType:h=>{let b=this.lookupDefinition(h);return b?fe(b)?b.operator.signature:ie(b)?b.value.type:Z.unknown:Z.unknown},hasSubscriptEvaluate:h=>{let b=this.lookupDefinition(h);return!!(ie(b)&&b.value.subscriptEvaluate)},isSymbolDeclared:h=>!!this.lookupDefinition(h),tolerance:this.tolerance,...this._latexOptions,...a,diagnostics:u,onDiagnostic:c,onBoundVariable:f});if(d===null)return null;let g=Yt(this,d,Pb({form:r,canonical:o,structural:s}));if(l!==void 0){if(g=g._unshared(),g.isCanonical)try{let h=new Set(g.symbols),b=new Set(g.freeVariables);for(let y of l){if(y.code!=="undeclared-symbol")continue;let x=y.detail?.name;typeof x=="string"&&(p.has(x)||h.has(x)&&!b.has(x)&&`${x}`)}}catch{}for(let h of l)h.detail&&Object.freeze(h.detail),Object.freeze(h);g.parseDiagnostics=Object.freeze(l)}return g}finally{iS(this)}}appliedNonFunctions(n){let t=this.latexSyntax;if(!t)return[];let i=t.parse(n,{getSymbolType:o=>{let s=this.lookupDefinition(o);return s?fe(s)?s.operator.signature:ie(s)?s.value.type:Z.unknown:Z.unknown},...this._latexOptions}),r=new Set;return i!==null&&hN(i,r),Array.from(r).sort()}function(n,t,i){let{canonical:r,structural:o}=Pb(i);return Rb(this,n,t,{metadata:i?.metadata,canonical:r,structural:o,scope:i?.scope})}error(n,t){return l0(this,n,t)}typeError(n,t,i){return WO(this,n,t,i)}hold(n){return this._fn("Hold",[this.expr(n,{form:"raw"})])}tuple(...n){return new Sn(this,"Tuple",n.map(t=>typeof t=="number"?this.number(t):t.canonical),{canonical:!0})}type(n){return n instanceof Z?n:new Z(n,this._typeResolver)}string(n,t){return new ea(this,n,t)}symbol(n,t){return GO(this,this._commonSymbols,n,t)}number(n,t){return UO(this,this._commonNumbers,n,t)}rules(n,t){return kp(this,n,t)}getRuleSet(n){if(n??="standard-simplification",n==="standard-simplification"){this._simplificationRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("standard-simplification-rules");let t=this._cache("standard-simplification-rules",()=>{let r=kp(this,this._simplificationRules.rules,{canonical:!0}).rules.filter(o=>o.purpose!=="expand");return{rules:AA(r)}});return this._simplificationRules.markCached(),t}if(n==="solve-univariate"){this._solveRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("univariate-roots-rules");let t=this._cache("univariate-roots-rules",()=>kp(this,this._solveRules.rules));return this._solveRules.markCached(),t}if(n==="harmonization"){this._harmonizationRules.hasMutatedSinceLastCache()&&this._cacheStore.invalidate("harmonization-rules");let t=this._cache("harmonization-rules",()=>kp(this,this._harmonizationRules.rules));return this._harmonizationRules.markCached(),t}}_fn(n,t,i){let r=i?.canonical??!0;return new Sn(this,n,t,{...i,canonical:r})}ask(n){return xS(this,n)}verify(n){return ES(this,n)}assume(n){return k6(this,n)}forget(n){vS(this,n)}};c0(()=>new yo);yo._latexSyntaxFactory=()=>new Ss;c0(()=>new yo({latexSyntax:new Ss}));globalThis[Symbol.for("io.cortexjs.compute-engine")]={ComputeEngine:yo.prototype.constructor,version:"0.86.2",LatexSyntax:Ss,LATEX_DICTIONARY:Aa,isExpression:Zd,isNumber:N,isSymbol:w,isFunction:m,isString:q,isTensor:Qt,isDictionary:Lt,isCollection:oy,isIndexedCollection:sy,numericValue:ze,sym:C};function bN(e){return e.fg===void 0&&e.bg===void 0&&(e.weight===void 0||e.weight==="normal")&&(e.italic===void 0||e.italic===!1)}var m0=class{width;indent;constructor(n){this.width=n?.width,this.indent=n?.indent??0}renderBlock(n){let t="spans"in n?this.renderSpans(n.spans):n.blocks.map(i=>this.renderBlock(i)).join(`
|
|
1583
1583
|
`);return n.tag==="paragraph"?`
|
|
1584
1584
|
${Id(t,this.width).join(`
|
|
1585
1585
|
`)}
|
|
@@ -1598,7 +1598,7 @@ ${Id(t,this.width).join(`
|
|
|
1598
1598
|
)`}choice(n){let t,i=1/0;return this.blocks.forEach(r=>{let o=r.cost(n);o<i&&(i=o,t=r)}),t}serialize(n){return this.choice(n).serialize(n)}nextCol(n){return this.choice(n).nextCol(n)}cost(n){return Math.min(...this.blocks.map(t=>t.cost(n)))}},T0=class{options;constructor(n){n?.indentChar==="space"?n.indentChar=" ":n?.indentChar==="tab"&&(n.indentChar=" "),this.options={cost:{softMargin:.05,margin:100,linebreak:2,commentLinebreak:.5,flowLinebreak:.3,callLinebreak:.5,argLinebreak:5,...n?.cost??{}},indentChar:" ",indentCharWidth:1,indentWidth:2,margin:80,softMargin:50,aroundInfixOperator:" ",aroundRelationalOperator:" ",afterSeparator:" ",...n??{}}}get cost(){return this.options.cost}get margin(){return this.options.margin}get softMargin(){return this.options.softMargin}indentChars(n=1){return(this.options.indentChar==="tab"?" ":" ").repeat(n*this.options.indentWidth)}indentLength(n=1){return n*this.options.indentWidth*this.options.indentCharWidth}linebreak(n,t){return!n&&!t?`
|
|
1599
1599
|
`:t?n+`
|
|
1600
1600
|
`+t:n+`
|
|
1601
|
-
`}countLinebreaks(n){return n.split(/\r\n|\r|\n/).length}normalizedBlocks(n){return n.map(t=>typeof t=="string"?new Er(this,t):t).filter(t=>!(t instanceof bu))}infixOperator(n){return new Er(this,this.options.aroundInfixOperator+n+this.options.aroundInfixOperator)}relationalOperator(n){return new Er(this,this.options.aroundRelationalOperator+n+this.options.aroundRelationalOperator)}separator(n){return new Er(this,n+this.options.afterSeparator)}fence(n){return new Er(this,n)}text(n){return!n||n.length===0?new bu(this):new Er(this,n)}line(...n){let t=this.normalizedBlocks(n),i=[],r="";for(let o of t)o instanceof Er?r?(i.pop(),r=r+o.s,i.push(new Er(this,r))):(i.push(o),r=o.s):(r="",i.push(o));return i.length===1?i[0]:new kc(this,...i)}stack(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new I0(this,...t)}wrap(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new ON(this,...t)}indent(n,t=1){return new kc(this,new Er(this,this.indentChars(t)),n)}choice(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new LN(this,...t)}fencedBlock(n,t,i){return t?this.fencedList(n,"",i,[t]):this.line(this.fence(n),this.fence(i))}fencedList(n,t,i,r){let o=this.fence(n),s=this.fence(i);if(r.length===0)return this.line(o,s);if(r.length===1)return this.line(o,r[0],s);let a=r.map(l=>this.line(l,t)),u=[...a];return u.pop(),u.push(r[r.length-1]),!n&&!i?this.choice(this.line(...u),this.wrap(...a)):this.choice(this.line(o,...u,s),this.stack(o,this.indent(this.stack(...a)),s))}list(n,t){return this.fencedList("",n,"",t)}};var Ac={positiveInfinity:"+Infinity",negativeInfinity:"-Infinity",notANumber:"NaN",imaginaryUnit:"i",decimalSeparator:".",digitGroupSeparator:"_",digitGroup:3,exponentProduct:"",beginExponentMarker:"e",endExponentMarker:"",truncationMarker:"",repeatingDecimal:"none",fractionalDigits:"max",notation:"auto",avoidExponentsInRange:[-7,20]};function q7(e,n){let t=new T0({...n?.fancySymbols?{aroundInfixOperator:"\u205F",aroundRelationalOperator:"\u2005",afterSeparator:"\u2009"}:{},...n});function i(v){if(v===null)return new bu(t);if(typeof v=="string"&&Bu(v)){let k=ce(v);if(k!==null)return r(k)}if(typeof v=="object"&&v!==null&&"str"in v)return r(v.str);let _=o(v),I;if(R(v)&&(I=y(v)??E(v)??x(v)),!I){let k=V(v);k!==null&&(I=t.text(yu(k)))}if(!I&&(typeof v=="number"||nr(v)||typeof v=="string"&&xi(v))){let k=$o(v,Ac);k&&(I=t.text(k))}if(!I){let k=Xc(v);if(k!==null){let A=k,P=Object.keys(k).map(B=>t.line(kd(B),t.relationalOperator("->"),i(A[B])));if(P.length===0)return t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}"));I=t.fencedList("{",t.separator(","),"}",P)}}return I?_ instanceof bu?I:t.choice(t.line(_,I),t.stack(_,I)):t.text()}function r(v){return t.text(`"${kd(v)}"`)}function o(v){return typeof v!="object"?t.text():"comment"in v&&v.comment&&v.comment.length>0?t.text(`/* ${v.comment} */`):t.text()}let s={};for(let v of RN)v.name in s||v.name!=="Range"&&(s[v.name]={symbol:v.symbol,fancySymbol:v.fancySymbol,precedence:v.precedence,unary:v.kind==="prefix",postfix:v.kind==="postfix",relational:v.relational});s.Divide&&!s.Rational&&(s.Rational={...s.Divide});let a=v=>v!==null&&(typeof v=="number"||nr(v)||typeof v=="string"&&xi(v)),u={BaseForm:v=>{let _=ne(M(v,2))??16,I=M(v,1),T=ne(I);return T===null||Number.isNaN(T)||!Number.isFinite(T)||!(_===2||_===10||_===16)?x(v):_===2?t.text("0b"+Number(T).toString(2)):_===10?t.text($o(I,Ac)):_===16?Number.isFinite(T)?Number.isInteger(T)?t.text("0x"+Number(T).toString(16)):t.text(pM(T)):t.text($o(I,Ac)):x(v)},String:v=>t.wrap('"',...Yn(v,_=>{let I=ce(_);return I!==null?t.text(kd(I)):t.fencedBlock("\\(",i(_),")")}),'"'),List:v=>t.fencedList("[",t.separator(","),"]",Yn(v,i)),Set:v=>Ee(v)===0?t.text("{}"):t.fencedList("{",t.separator(","),"}",Yn(v,i)),Tuple:v=>Ee(v)<2?x(v):t.fencedList("(",t.separator(","),")",Yn(v,i)),At:v=>{let _=M(v,1),I=F(v).slice(1);if(_===null||I.length===0)return x(v);let T=s[R(_)]!==void 0?t.line("(",i(_),")"):i(_);return t.line(T,t.fencedList("[",t.separator(","),"]",I.map(k=>i(k))))},Dictionary:v=>Ee(v)===0?t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}")):t.fencedList("{",t.separator(","),"}",Yn(v,i)),Negate:v=>{if(Ee(v)!==1)return x(v);let _=M(v,1);return a(_)?t.text(bK($o(_,Ac))):E(v)??x(v)},Multiply:v=>{let _=F(v);if(_.length===2&&a(_[0])){let I=V(_[1]);if(I!==null){let T=$o(_[0],Ac);if(yK(T,I))return t.text(T+I)}}return E(v)??x(v)},Block:v=>Ee(v)===0?t.text("do {}"):t.line("do ",t.fencedList("{",t.separator(";"),"}",Yn(v,i))),Function:v=>{let _=F(v).slice(1),I=M(v,1),T=_.some(B=>R(B)==="Typed"),k=R(I)==="Typed";if(!T&&!k)return x(v);let{bodyExpr:A}=d(v),P=n?.fancySymbols?"\u21A6":"|->";return t.line(h(_),` ${P} `,i(A))},Typed:v=>i(M(v,1)),Assign:v=>{let _=M(v,1),I=M(v,2);if(_!==null&&I!==null&&R(I)==="Function"){let T=F(I).slice(1),k=M(I,1),A=T.some(B=>R(B)==="Typed"),P=R(k)==="Typed";if(A||P)return b(_,I)}return E(v)??x(v)},Match:v=>{let _=M(v,1),I=F(v).slice(1),T=t.line("match ",i(_)," {");return I.length===0?t.line("match ",i(_)," {}"):t.stack(T,t.indent(t.stack(...I.map(l))),t.text("}"))},MatchCase:v=>l(v),Pin:v=>c(v),Alternatives:v=>c(v)};function l(v){let _=F(v),I=c(_[0]??"Nothing"),T=_.length>=3,k=T?_[1]:null,A=T?_[2]:_[1],P=[I];return k!=null&&P.push(" if ",i(k)),P.push(" => ",i(A??"Nothing")),t.line(...P)}function c(v){let _=R(v);if(_==="Pin")return t.line("== ",i(M(v,1)));if(_==="Alternatives"){let k=F(v),A=[];return k.forEach((P,B)=>{B>0&&A.push(" | "),A.push(c(P))}),t.line(...A)}if(_==="List")return t.fencedList("[",t.separator(","),"]",F(v).map(c));if(_==="Tuple")return t.fencedList("(",t.separator(","),")",F(v).map(c));if(_==="Dictionary"){let k=F(v);return k.length===0?t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}")):t.fencedList("{",t.separator(","),"}",k.map(A=>t.line(i(M(A,1)),t.relationalOperator("->"),c(M(A,2)??"Nothing"))))}let I=V(v);if(I!==null)return I==="_"?t.text("_"):I==="True"?t.text("true"):I==="False"?t.text("false"):I.startsWith("___")?t.text("..."+I.slice(3)):I.startsWith("_")?t.text(yu(I.slice(1))):t.line("== ",t.text(yu(I)));if(a(v))return t.text($o(v,Ac));if(typeof v=="object"&&v!==null&&"str"in v)return r(v.str);let T=typeof v=="string"&&/^'[\s\S]*'$/.test(v)?ce(v):null;return T!==null?r(T):i(f(v))}function f(v){let _=V(v);if(_!==null)return _!=="_"&&!_.startsWith("___")&&_.startsWith("_")?{sym:_.slice(1)}:v;let I=R(v);return I?{fn:[I,...F(v).map(f)]}:v}let p=v=>{if(v===null)return null;let _=ce(v);return _!==null?_:V(v)},d=v=>{let _=M(v,1);return R(_)==="Typed"?{bodyExpr:M(_,1),retType:p(M(_,2))}:{bodyExpr:_,retType:null}},g=v=>{let _=R(v)==="Typed",I=_?V(M(v,1)):V(v),T=I!==null?yu(I):"",k=_?p(M(v,2)):null;return t.text(k!==null?`${T}: ${k}`:T)},h=v=>t.fencedList("(",t.separator(","),")",v.map(g)),b=(v,_)=>{let I=V(v),T=I!==null?yu(I):"",k=F(_).slice(1),{bodyExpr:A,retType:P}=d(_),B=P!==null?` -> ${P}`:"";return R(A)==="Block"?t.line(`function ${T}`,h(k),`${B} `,t.fencedList("{",t.separator(";"),"}",Yn(A,i))):t.line(T,h(k),`${B} = `,i(A))};function y(v){return u[R(v)]?.(v)??null}function x(v){let _=R(v);return _?t.line(yu(_),t.fencedList("(",t.separator(","),")",Yn(v,i))):t.line("Apply(",i(_),t.separator(","),t.fencedList("[",t.separator(","),"]",Yn(v,i)),")")}function E(v){let _=R(v);if(!_)return null;let I=s[_];if(!I)return null;let T=n?.fancySymbols?I.fancySymbol??I.symbol:I.symbol;if(I.unary){if(Ee(v)!==1)return null;let A=M(v,1),P=R(A),B=s[P];return B&&B.precedence<I.precedence?t.line(T,"(",i(A),")"):t.line(T,i(A))}if(I.postfix){if(Ee(v)!==1)return null;let A=M(v,1),P=R(A),B=s[P];return B&&B.precedence<=I.precedence?t.line("(",i(A),")",T):t.line(i(A),T)}let k=Yn(v,A=>{let P=R(A),B=s[P];return B&&B.precedence<I.precedence?t.line("(",i(A),")"):i(A)});return k?t.list(I.relational?t.relationalOperator(T):t.infixOperator(T),k):null}return R(e)==="Block"&&Ee(e)>=2?t.stack(...Yn(e,i)).serialize(0):i(e).serialize(0)}function bK(e){return e.startsWith("-")?e.slice(1):e.startsWith("+")?"-"+e.slice(1):"-"+e}function yK(e,n){return!(!/^\d[\d_]*(\.\d[\d_]*)?$/.test(e)||yu(n)!==n||!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n)||/^[eE]/.test(n)||e==="0"&&/^[bBxX]/.test(n))}function $7(e){return h0.has(e)?h0.get(e):NN(e)?e<65536?`\\u${("0000"+e.toString(16)).slice(-4)}`:`\\u{${("000000000"+e.toString(16)).slice(-8)}}`:String.fromCodePoint(e)}function kd(e){let n="",t=af(e);if(typeof t=="string")for(let i of t)n+=$7(i.codePointAt(0));else for(let i of t)i.length===1?n+=$7(i.codePointAt(0)):n+=i;return n}function yu(e){if(E0.has(e))return`\`${e}\``;if(/^[a-zA-Z][a-zA-Z\d_]*$/.test(e))return e;let n=e.codePointAt(0);if(Yi.has(n))return`\`${kd(e)}\``;let t=!1,i=af(e),r=0;for(;!t&&r<i.length;){let o=i[r].codePointAt(0);t=h0.has(o)||NN(o)||wc(o),r+=1}return t?`\`${kd(e)}\``:e}function J7(e,n,t){let i=[],r;try{let[u,l]=w0(n,t?.url,{parseLatex:t?.parseLatex,allowHostPragmas:t?.allowHostPragmas??!1});r=u,i.push(...l)}catch(u){if(u instanceof Ic)return i.push(V7(["error-directive",u.message],[0,n.length])),{value:e.Nothing,diagnostics:i};throw u}let o=R(r)==="Block"?[...F(r)]:[r],s=e.Nothing,a=new Set;for(let u=0;u<o.length;u++){let l=o[u],c;try{s=e.box(l).evaluate()}catch(f){let p=f instanceof Error?f.message:String(f);c=xK(f),s=c!==void 0?e.box(["Error",{str:p},{str:c}]):e.box(["Error",{str:p}])}if(u<o.length-1){let f=s.errors;f.length>0&&i.push(V7(c!==void 0?["evaluation-canceled",c,f[0].toString()]:["runtime-error",f[0].toString()],j7(l,n)))}z7(e,s.json,a,i,l,n)}return{value:s,diagnostics:i}}function j7(e,n){return(typeof e=="object"&&e!==null&&!Array.isArray(e)?e.sourceOffsets:void 0)??[0,n.length]}function z7(e,n,t,i,r,o){let s=R(n);if(s!==""){if(!t.has(s)&&e.operatorInfo(s)===void 0){t.add(s);let a=e.suggestOperatorName(s);a!==void 0&&i.push({severity:"warning",message:["unknown-function",s,a],range:j7(r,o)})}for(let a of F(n))z7(e,a,t,i,r,o)}}function xK(e){if(!(e instanceof Error)||e.name!=="CancellationError")return;let n=e.cause;if(n==="timeout"||n==="iteration-limit-exceeded"||n==="recursion-depth-exceeded")return n}function V7(e,n){return{severity:"error",message:e,range:n}}var EK="0.86.1";return X7(vK);})();
|
|
1601
|
+
`}countLinebreaks(n){return n.split(/\r\n|\r|\n/).length}normalizedBlocks(n){return n.map(t=>typeof t=="string"?new Er(this,t):t).filter(t=>!(t instanceof bu))}infixOperator(n){return new Er(this,this.options.aroundInfixOperator+n+this.options.aroundInfixOperator)}relationalOperator(n){return new Er(this,this.options.aroundRelationalOperator+n+this.options.aroundRelationalOperator)}separator(n){return new Er(this,n+this.options.afterSeparator)}fence(n){return new Er(this,n)}text(n){return!n||n.length===0?new bu(this):new Er(this,n)}line(...n){let t=this.normalizedBlocks(n),i=[],r="";for(let o of t)o instanceof Er?r?(i.pop(),r=r+o.s,i.push(new Er(this,r))):(i.push(o),r=o.s):(r="",i.push(o));return i.length===1?i[0]:new kc(this,...i)}stack(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new I0(this,...t)}wrap(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new ON(this,...t)}indent(n,t=1){return new kc(this,new Er(this,this.indentChars(t)),n)}choice(...n){let t=this.normalizedBlocks(n);return t.length===1?t[0]:new LN(this,...t)}fencedBlock(n,t,i){return t?this.fencedList(n,"",i,[t]):this.line(this.fence(n),this.fence(i))}fencedList(n,t,i,r){let o=this.fence(n),s=this.fence(i);if(r.length===0)return this.line(o,s);if(r.length===1)return this.line(o,r[0],s);let a=r.map(l=>this.line(l,t)),u=[...a];return u.pop(),u.push(r[r.length-1]),!n&&!i?this.choice(this.line(...u),this.wrap(...a)):this.choice(this.line(o,...u,s),this.stack(o,this.indent(this.stack(...a)),s))}list(n,t){return this.fencedList("",n,"",t)}};var Ac={positiveInfinity:"+Infinity",negativeInfinity:"-Infinity",notANumber:"NaN",imaginaryUnit:"i",decimalSeparator:".",digitGroupSeparator:"_",digitGroup:3,exponentProduct:"",beginExponentMarker:"e",endExponentMarker:"",truncationMarker:"",repeatingDecimal:"none",fractionalDigits:"max",notation:"auto",avoidExponentsInRange:[-7,20]};function q7(e,n){let t=new T0({...n?.fancySymbols?{aroundInfixOperator:"\u205F",aroundRelationalOperator:"\u2005",afterSeparator:"\u2009"}:{},...n});function i(v){if(v===null)return new bu(t);if(typeof v=="string"&&Bu(v)){let k=ce(v);if(k!==null)return r(k)}if(typeof v=="object"&&v!==null&&"str"in v)return r(v.str);let _=o(v),I;if(R(v)&&(I=y(v)??E(v)??x(v)),!I){let k=V(v);k!==null&&(I=t.text(yu(k)))}if(!I&&(typeof v=="number"||nr(v)||typeof v=="string"&&xi(v))){let k=$o(v,Ac);k&&(I=t.text(k))}if(!I){let k=Xc(v);if(k!==null){let A=k,P=Object.keys(k).map(B=>t.line(kd(B),t.relationalOperator("->"),i(A[B])));if(P.length===0)return t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}"));I=t.fencedList("{",t.separator(","),"}",P)}}return I?_ instanceof bu?I:t.choice(t.line(_,I),t.stack(_,I)):t.text()}function r(v){return t.text(`"${kd(v)}"`)}function o(v){return typeof v!="object"?t.text():"comment"in v&&v.comment&&v.comment.length>0?t.text(`/* ${v.comment} */`):t.text()}let s={};for(let v of RN)v.name in s||v.name!=="Range"&&(s[v.name]={symbol:v.symbol,fancySymbol:v.fancySymbol,precedence:v.precedence,unary:v.kind==="prefix",postfix:v.kind==="postfix",relational:v.relational});s.Divide&&!s.Rational&&(s.Rational={...s.Divide});let a=v=>v!==null&&(typeof v=="number"||nr(v)||typeof v=="string"&&xi(v)),u={BaseForm:v=>{let _=ne(M(v,2))??16,I=M(v,1),T=ne(I);return T===null||Number.isNaN(T)||!Number.isFinite(T)||!(_===2||_===10||_===16)?x(v):_===2?t.text("0b"+Number(T).toString(2)):_===10?t.text($o(I,Ac)):_===16?Number.isFinite(T)?Number.isInteger(T)?t.text("0x"+Number(T).toString(16)):t.text(pM(T)):t.text($o(I,Ac)):x(v)},String:v=>t.wrap('"',...Yn(v,_=>{let I=ce(_);return I!==null?t.text(kd(I)):t.fencedBlock("\\(",i(_),")")}),'"'),List:v=>t.fencedList("[",t.separator(","),"]",Yn(v,i)),Set:v=>Ee(v)===0?t.text("{}"):t.fencedList("{",t.separator(","),"}",Yn(v,i)),Tuple:v=>Ee(v)<2?x(v):t.fencedList("(",t.separator(","),")",Yn(v,i)),At:v=>{let _=M(v,1),I=F(v).slice(1);if(_===null||I.length===0)return x(v);let T=s[R(_)]!==void 0?t.line("(",i(_),")"):i(_);return t.line(T,t.fencedList("[",t.separator(","),"]",I.map(k=>i(k))))},Dictionary:v=>Ee(v)===0?t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}")):t.fencedList("{",t.separator(","),"}",Yn(v,i)),Negate:v=>{if(Ee(v)!==1)return x(v);let _=M(v,1);return a(_)?t.text(bK($o(_,Ac))):E(v)??x(v)},Multiply:v=>{let _=F(v);if(_.length===2&&a(_[0])){let I=V(_[1]);if(I!==null){let T=$o(_[0],Ac);if(yK(T,I))return t.text(T+I)}}return E(v)??x(v)},Block:v=>Ee(v)===0?t.text("do {}"):t.line("do ",t.fencedList("{",t.separator(";"),"}",Yn(v,i))),Function:v=>{let _=F(v).slice(1),I=M(v,1),T=_.some(B=>R(B)==="Typed"),k=R(I)==="Typed";if(!T&&!k)return x(v);let{bodyExpr:A}=d(v),P=n?.fancySymbols?"\u21A6":"|->";return t.line(h(_),` ${P} `,i(A))},Typed:v=>i(M(v,1)),Assign:v=>{let _=M(v,1),I=M(v,2);if(_!==null&&I!==null&&R(I)==="Function"){let T=F(I).slice(1),k=M(I,1),A=T.some(B=>R(B)==="Typed"),P=R(k)==="Typed";if(A||P)return b(_,I)}return E(v)??x(v)},Match:v=>{let _=M(v,1),I=F(v).slice(1),T=t.line("match ",i(_)," {");return I.length===0?t.line("match ",i(_)," {}"):t.stack(T,t.indent(t.stack(...I.map(l))),t.text("}"))},MatchCase:v=>l(v),Pin:v=>c(v),Alternatives:v=>c(v)};function l(v){let _=F(v),I=c(_[0]??"Nothing"),T=_.length>=3,k=T?_[1]:null,A=T?_[2]:_[1],P=[I];return k!=null&&P.push(" if ",i(k)),P.push(" => ",i(A??"Nothing")),t.line(...P)}function c(v){let _=R(v);if(_==="Pin")return t.line("== ",i(M(v,1)));if(_==="Alternatives"){let k=F(v),A=[];return k.forEach((P,B)=>{B>0&&A.push(" | "),A.push(c(P))}),t.line(...A)}if(_==="List")return t.fencedList("[",t.separator(","),"]",F(v).map(c));if(_==="Tuple")return t.fencedList("(",t.separator(","),")",F(v).map(c));if(_==="Dictionary"){let k=F(v);return k.length===0?t.line(t.fence("{"),t.relationalOperator("->"),t.fence("}")):t.fencedList("{",t.separator(","),"}",k.map(A=>t.line(i(M(A,1)),t.relationalOperator("->"),c(M(A,2)??"Nothing"))))}let I=V(v);if(I!==null)return I==="_"?t.text("_"):I==="True"?t.text("true"):I==="False"?t.text("false"):I.startsWith("___")?t.text("..."+I.slice(3)):I.startsWith("_")?t.text(yu(I.slice(1))):t.line("== ",t.text(yu(I)));if(a(v))return t.text($o(v,Ac));if(typeof v=="object"&&v!==null&&"str"in v)return r(v.str);let T=typeof v=="string"&&/^'[\s\S]*'$/.test(v)?ce(v):null;return T!==null?r(T):i(f(v))}function f(v){let _=V(v);if(_!==null)return _!=="_"&&!_.startsWith("___")&&_.startsWith("_")?{sym:_.slice(1)}:v;let I=R(v);return I?{fn:[I,...F(v).map(f)]}:v}let p=v=>{if(v===null)return null;let _=ce(v);return _!==null?_:V(v)},d=v=>{let _=M(v,1);return R(_)==="Typed"?{bodyExpr:M(_,1),retType:p(M(_,2))}:{bodyExpr:_,retType:null}},g=v=>{let _=R(v)==="Typed",I=_?V(M(v,1)):V(v),T=I!==null?yu(I):"",k=_?p(M(v,2)):null;return t.text(k!==null?`${T}: ${k}`:T)},h=v=>t.fencedList("(",t.separator(","),")",v.map(g)),b=(v,_)=>{let I=V(v),T=I!==null?yu(I):"",k=F(_).slice(1),{bodyExpr:A,retType:P}=d(_),B=P!==null?` -> ${P}`:"";return R(A)==="Block"?t.line(`function ${T}`,h(k),`${B} `,t.fencedList("{",t.separator(";"),"}",Yn(A,i))):t.line(T,h(k),`${B} = `,i(A))};function y(v){return u[R(v)]?.(v)??null}function x(v){let _=R(v);return _?t.line(yu(_),t.fencedList("(",t.separator(","),")",Yn(v,i))):t.line("Apply(",i(_),t.separator(","),t.fencedList("[",t.separator(","),"]",Yn(v,i)),")")}function E(v){let _=R(v);if(!_)return null;let I=s[_];if(!I)return null;let T=n?.fancySymbols?I.fancySymbol??I.symbol:I.symbol;if(I.unary){if(Ee(v)!==1)return null;let A=M(v,1),P=R(A),B=s[P];return B&&B.precedence<I.precedence?t.line(T,"(",i(A),")"):t.line(T,i(A))}if(I.postfix){if(Ee(v)!==1)return null;let A=M(v,1),P=R(A),B=s[P];return B&&B.precedence<=I.precedence?t.line("(",i(A),")",T):t.line(i(A),T)}let k=Yn(v,A=>{let P=R(A),B=s[P];return B&&B.precedence<I.precedence?t.line("(",i(A),")"):i(A)});return k?t.list(I.relational?t.relationalOperator(T):t.infixOperator(T),k):null}return R(e)==="Block"&&Ee(e)>=2?t.stack(...Yn(e,i)).serialize(0):i(e).serialize(0)}function bK(e){return e.startsWith("-")?e.slice(1):e.startsWith("+")?"-"+e.slice(1):"-"+e}function yK(e,n){return!(!/^\d[\d_]*(\.\d[\d_]*)?$/.test(e)||yu(n)!==n||!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n)||/^[eE]/.test(n)||e==="0"&&/^[bBxX]/.test(n))}function $7(e){return h0.has(e)?h0.get(e):NN(e)?e<65536?`\\u${("0000"+e.toString(16)).slice(-4)}`:`\\u{${("000000000"+e.toString(16)).slice(-8)}}`:String.fromCodePoint(e)}function kd(e){let n="",t=af(e);if(typeof t=="string")for(let i of t)n+=$7(i.codePointAt(0));else for(let i of t)i.length===1?n+=$7(i.codePointAt(0)):n+=i;return n}function yu(e){if(E0.has(e))return`\`${e}\``;if(/^[a-zA-Z][a-zA-Z\d_]*$/.test(e))return e;let n=e.codePointAt(0);if(Yi.has(n))return`\`${kd(e)}\``;let t=!1,i=af(e),r=0;for(;!t&&r<i.length;){let o=i[r].codePointAt(0);t=h0.has(o)||NN(o)||wc(o),r+=1}return t?`\`${kd(e)}\``:e}function J7(e,n,t){let i=[],r;try{let[u,l]=w0(n,t?.url,{parseLatex:t?.parseLatex,allowHostPragmas:t?.allowHostPragmas??!1});r=u,i.push(...l)}catch(u){if(u instanceof Ic)return i.push(V7(["error-directive",u.message],[0,n.length])),{value:e.Nothing,diagnostics:i};throw u}let o=R(r)==="Block"?[...F(r)]:[r],s=e.Nothing,a=new Set;for(let u=0;u<o.length;u++){let l=o[u],c;try{s=e.box(l).evaluate()}catch(f){let p=f instanceof Error?f.message:String(f);c=xK(f),s=c!==void 0?e.box(["Error",{str:p},{str:c}]):e.box(["Error",{str:p}])}if(u<o.length-1){let f=s.errors;f.length>0&&i.push(V7(c!==void 0?["evaluation-canceled",c,f[0].toString()]:["runtime-error",f[0].toString()],j7(l,n)))}z7(e,s.json,a,i,l,n)}return{value:s,diagnostics:i}}function j7(e,n){return(typeof e=="object"&&e!==null&&!Array.isArray(e)?e.sourceOffsets:void 0)??[0,n.length]}function z7(e,n,t,i,r,o){let s=R(n);if(s!==""){if(!t.has(s)&&e.operatorInfo(s)===void 0){t.add(s);let a=e.suggestOperatorName(s);a!==void 0&&i.push({severity:"warning",message:["unknown-function",s,a],range:j7(r,o)})}for(let a of F(n))z7(e,a,t,i,r,o)}}function xK(e){if(!(e instanceof Error)||e.name!=="CancellationError")return;let n=e.cause;if(n==="timeout"||n==="iteration-limit-exceeded"||n==="recursion-depth-exceeded")return n}function V7(e,n){return{severity:"error",message:e,range:n}}var EK="0.86.2";return X7(vK);})();
|
|
1602
1602
|
/*! Bundled license information:
|
|
1603
1603
|
|
|
1604
1604
|
complex-esm/dist/src/complex.js:
|