@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/core.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** ComputeEngineCore 0.86.
|
|
1
|
+
/** ComputeEngineCore 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.ComputeEngineCore = {}));})(this, (function (exports) { 'use strict';
|
|
3
3
|
"use strict";var ComputeEngineCore=(()=>{var Gb=Object.defineProperty;var w7=Object.getOwnPropertyDescriptor;var T7=Object.getOwnPropertyNames;var M7=Object.prototype.hasOwnProperty;var C7=(e,n)=>{for(var t in n)Gb(e,t,{get:n[t],enumerable:!0})},A7=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of T7(n))!M7.call(e,r)&&r!==t&&Gb(e,r,{get:()=>n[r],enumerable:!(i=w7(n,r))||i.enumerable});return e};var k7=e=>A7(Gb({},"__esModule",{value:!0}),e);var sW={};C7(sW,{CancellationError:()=>Ce,ComputeEngine:()=>Qp,N:()=>lS,assign:()=>cS,declare:()=>fS,evaluate:()=>aS,expand:()=>pS,expandAll:()=>mS,expr:()=>sS,factor:()=>gS,getDefaultEngine:()=>Hs,isCollection:()=>bN,isDictionary:()=>Yt,isExpression:()=>gd,isFunction:()=>m,isIndexedCollection:()=>yN,isNumber:()=>N,isString:()=>B,isSymbol:()=>I,isTensor:()=>mi,numericValue:()=>He,simplify:()=>uS,solve:()=>dS,version:()=>oW});var vt=Math.cosh||function(e){return Math.abs(e)<1e-9?1-e:(Math.exp(e)+Math.exp(-e))*.5},Mi=Math.sinh||function(e){return Math.abs(e)<1e-9?e:(Math.exp(e)-Math.exp(-e))*.5},R7=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)},P7=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))},ta=function(){throw SyntaxError("Invalid Param")};function Ub(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 D7=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 F.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 F.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]):ta();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&&ta();for(var s=0;s<i.length;s++){var u=i[s];u===" "||u===" "||u===`
|
|
4
4
|
`||(u==="+"?r++:u==="-"?o++:u==="i"||u==="I"?(r+o===0&&ta(),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(u)))&&ta(),i[s+1]==="i"||i[s+1]==="I"?(t.im+=parseFloat((o%2?"-":"")+u),s++):t.re+=parseFloat((o%2?"-":"")+u),r=o=0))}r+o>0&&ta();break;case"number":t.im=0,t.re=e;break;default:ta()}return isNaN(t.re)||isNaN(t.im),t},F=class e{constructor(n,t){this.re=0,this.im=0;var i=D7(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,u;return o===0?new e(n/r,t/r):Math.abs(r)<Math.abs(o)?(u=r/o,s=r*u+o,new e((n*u+t)/s,(t*u-n)/s)):(u=o/r,s=o*u+r,new e((n+t*u)/s,(t-n*u)/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=Ub(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)+R7(t),Math.exp(n)*Math.sin(t))}log(){var n=this.re,t=this.im;return t===0&&n>0,new e(Ub(n,t),Math.atan2(t,n))}abs(){return P7(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)*Mi(t))}cos(){var n=this.re,t=this.im;return new e(Math.cos(n)*vt(t),-Math.sin(n)*Mi(t))}tan(){var n=2*this.re,t=2*this.im,i=Math.cos(n)+vt(t);return new e(Math.sin(n)/i,Mi(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,Mi(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)*Mi(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)*Mi(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(Mi(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),Mi(n)*Math.sin(t))}tanh(){var n=2*this.re,t=2*this.im,i=vt(n)+Math.cos(t);return new e(Mi(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(Mi(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*Mi(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*Mi(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,u=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),a=u.re;return u.re=Ub(u.re,u.im)/2,u.im=Math.atan2(u.im,a)/2,i&&(u.im=-u.im),u}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())}};F.ZERO=new F(0,0);F.ONE=new F(1,0);F.I=new F(0,1);F.PI=new F(Math.PI,0);F.E=new F(Math.E,0);F.INFINITY=new F(1/0,1/0);F.NAN=new F(NaN,NaN);F.EPSILON=1e-15;var wS=new Map,O7=1e5;function $e(e){if(e<=O7){let n=wS.get(e);return n===void 0&&(n=10n**BigInt(e),wS.set(e,n)),n}return 10n**BigInt(e)}function lo(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 MS(e,n,t){return e*n>>BigInt(t)}function CS(e,n,t){return(e<<BigInt(t))/n}function td(e,n){if(e===0n)return 0n;if(e<0n)throw new RangeError("fpsqrt: negative input");let t=e<<BigInt(n),i;if(n<F7){i=Hb(t);let u;do u=i,i=(i+t/i)/2n;while(Ci(i-u)>1n)}else i=Yb(t,lo(t));let r=(i+t/i)/2n,o=Ci(i*i-t);return Ci(r*r-t)<o?r:i}function Hb(e){let n=lo(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 AS=1024,F7=640;function Yb(e,n){if(n<AS){let o=Hb(e),s;do s=o,o=(o+e/o)/2n;while(Ci(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=Yb(e>>BigInt(t),n-t)<<BigInt(t>>1),r;do r=i,i=(i+e/i)/2n;while(Ci(i-r)>1n);for(;i*i>e;)i-=1n;for(;(i+1n)*(i+1n)<=e;)i+=1n;return i}function Ci(e){return e<0n?-e:e}function ra(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<$e(t-1);)t--;for(;e>=$e(t);)t++;return t}var L7=.7;function Wb(e,n){if(e===0n)return 1n<<BigInt(n);let t=Math.round(L7*Math.sqrt(n)),i=t+8,r=n+i,o=BigInt(r),s=1n<<o,u=BigInt(i),a=e<<u,l=a<0n,f=l?-a:a,c=Math.max(0,lo(f)-r+t);f>>=BigInt(c),a=l?-f:f;let p=s,d=a;p+=d;for(let g=2;d=(d*a>>o)/BigInt(g),d!==0n;g++)p+=d;for(let g=0;g<c;g++)p=p*p>>o;return p+(1n<<u-1n)>>u}var $7=4e4;function Qb(e,n){let t=1n<<BigInt(n);if(e<=0n)throw new RangeError("fpln: input must be positive");return e===t?0n:n>=$7?V7(e,n):B7(e,n)}function B7(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 u=e*Wb(-s,n)>>t,l=(u-i<<t)/(u+i),f=l<0n?-l:l,c=f*f>>t,p=f,d=f;for(let g=3n;p=p*c>>t,p!==0n;g+=2n)d+=p/g;return s+(l<0n?-2n:2n)*d}var Ws=null;function q7(e){if(Ws!==null){if(Ws.bits===e)return Ws.value;if(Ws.bits>e)return Ws.value>>BigInt(Ws.bits-e)}let n=Math.ceil(e*id)+12,t;if(n<=TS.length){let i=TS.slice(0,n);t=(BigInt(i)<<BigInt(e))/$e(i.length)}else t=Z7(e);return Ws={bits:e,value:t},t}function V7(e,n){let t=BigInt(n),i=lo(e)-n,r=Math.max(2,Math.ceil(n/2+4-i)),o=e<<BigInt(r-2),s=1n<<t,u=o;for(;Ci(s-u)>1n;){let l=s+u>>1n;u=of(s*u),s=l}return nd(n)*o/(2n*s)-BigInt(r)*q7(n)}var ia="314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837297804995105973173281609631859502445945534690830264252230825334468503526193118817101000313783875288658753320838142061717766914730359825349042875546873115956286388235378759375195778185778053217122680661300192787661119590921642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151557485724245415069595082953311686172785588907509838175463746493931925506040092770167113900984882401285836160356370766010471018194295559619894676783744944825537977472684710404753464620804668425906949129331367702898915210475216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992458631503028618297455570674983850549458858692699569092721079750930295532116534498720275596023648066549911988183479775356636980742654252786255181841757467289097777279380008164706001614524919217321721477235014144197356854816136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179049460165346680498862723279178608578438382796797668145410095388378636095068006422512520511739298489608412848862694560424196528502221066118630674427862203919494504712371378696095636437191728746776465757396241389086583264599581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745530506820349625245174939965143142980919065925093722169646151570985838741059788595977297549893016175392846813826868386894277415599185592524595395943104997252468084598727364469584865383673622262609912460805124388439045124413654976278079771569143599770012961608944169486855584840635",id=Math.log10(2),TS="693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687542001481020570685733685520235758130557032670751635075961930727570828371435190307038623891673471123350115364497955239120475172681574932065155524734139525882950453007095326366642654104239157814952043740430385500801944170641671518644712839968171784546957026271631064546150257207402481637773389638550695260668341137273873722928956493547025762652098859693201965058554764703306793654432547632744951250406069438147104689946506220167720424524529612687946546193165174681392672504103802546259656869144192871608293803172714367782654877566485085674077648451464439940461422603193096735402574446070308096085047486638523138181676751438667476647890881437141985494231519973548803751658612753529166100071053558249879414729509293113897155998205654392871700072180857610252368892132449713893203784393530887748259701715591070882368362758984258918535302436342143670611892367891923723146723217205340164925687274778234453534764811494186423867767744060695626573796008670762571991847340226514628379048830620330611446300737194890027436439650025809365194430411911506080948793067865158870900605203468429736193841289652556539686022194122924207574321757489097706752687115817051137009158942665478595964890653058460258668382940022833005382074005677053046787001841624044188332327983863490015631218895606505531512721993983320307514084260914790012651682434438935724727882054862715527418772430024897945401961872339808608316648114909306675193393128904316413706813977764981769748689038877899912965036192707108892641052309247839173735012298424204995689359922066022046549415106139187885744245577510206837030866619480896412186807790208181588580001688115973056186676199187395200766719214592236720602539595436541655311295175989940056000366513567569051245926825743946483168332624901803824240824231452306140963805700702551387702681785163069025513703234053802145019015374029509942262995779647427138157363801729873940704242179972266962979939312706935747240493386530879758721699645129446491883771156701678598804981838896784134938314014073166472765327635919233511233389338709513209059272185471328975470797891384445466676192702885533423429899321803769154973340267546758873236778342916191810430116091695265547859732891763545556742863877463987101912431754255888301206779210280341206879759143081283307230300883494705792496591005860012341561757413272465943",j7=13591409n,z7=545140134n,J7=10939058860032000n,G7=47.11;function ed(e,n){if(n-e===1){let l,f;if(e===0)l=1n,f=1n;else{l=BigInt(6*e-5)*BigInt(2*e-1)*BigInt(6*e-1);let p=BigInt(e);f=p*p*p*J7}let c=l*(j7+z7*BigInt(e));return e&1&&(c=-c),[l,f,c]}let t=e+n>>1,[i,r,o]=ed(e,t),[s,u,a]=ed(t,n);return[i*s,r*u,u*o+i*a]}function kS(e){return Math.max(2,Math.floor(e/G7)+3)}function U7(e){let[,n,t]=ed(0,kS(e)),i=1n<<BigInt(e),r=of(10005n*i*i);return n*426880n*r/t}function RS(e){let[,n,t]=ed(0,kS(Math.ceil(e/id))),i=$e(e),r=of(10005n*i*i);return n*426880n*r/t}function Zb(e,n){if(n-e===1){let l=e===0?1n:BigInt(2*e-1),f=e===0?1n:9n*BigInt(2*e+1);return[l,f,l]}let t=e+n>>1,[i,r,o]=Zb(e,t),[s,u,a]=Zb(t,n);return[i*s,r*u,u*o+i*a]}function Z7(e){let n=Math.max(2,Math.ceil(e/3.169925)+5),[,t,i]=Zb(0,n);return(i<<BigInt(e+1))/(3n*t)}function of(e){if(e<0n)throw new RangeError("bigintSqrt: negative input");if(e===0n)return 0n;let n=lo(e);if(n>=AS)return Yb(e,n);let t=Hb(e),i;do i=t,t=(t+e/t)/2n;while(Ci(t-i)>1n);for(;t*t>e;)t-=1n;for(;(t+1n)*(t+1n)<=e;)t+=1n;return t}var Qs=null;function nd(e){if(Qs!==null){if(Qs.bits===e)return Qs.value;if(Qs.bits>e)return Qs.value>>BigInt(Qs.bits-e)}let n=H7(e);return Qs={bits:e,value:n},n}function H7(e){let n=Math.ceil(e*id)+12;if(n+1<=ia.length){let t=ia.slice(0,n+1);return(BigInt(t)<<BigInt(e))/$e(t.length-1)}return U7(e)}function rd(e,n){let t=BigInt(n),i=1n<<t;if(e===0n)return[0n,i];let r=nd(n),o=2n*r,s=r/2n,u,a=Ci(e);if(a>i<<30n){let _=lo(a)-n+64,w=n+_,M=e<<BigInt(_),k=2n*nd(w),D=M%k;D<0n&&(D+=k),u=D>>BigInt(_)}else u=e%o;u<0n&&(u+=o);let l=1n,f=1n;u>3n*s?(u=o-u,l=-1n):u>r?(u=u-r,l=-1n,f=-1n):u>s&&(u=r-u,f=-1n);let c=Math.round(n*id),p=Math.min(18,Math.max(2,Math.ceil(.87*Math.sqrt(c)))),d=0,g=i>>BigInt(p);for(;u>g;)u=u/2n,d++;let h=u,b=i,y=u,x=i,v=u*u,S=2n*t;for(let _=2;;_+=2){if(x=(x*v>>S)/(BigInt(_)*BigInt(_-1)),x===0n){y=(y*v>>S)/(BigInt(_+1)*BigInt(_)),y!==0n&&(_%4===2?(b-=x,h-=y):(b+=x,h+=y));break}if(y=(y*v>>S)/(BigInt(_+1)*BigInt(_)),_%4===2?(b-=x,h-=y):(b+=x,h+=y),y===0n)break}for(let _=0;_<d;_++){let w=2n*h*b>>t,M=(2n*b*b>>t)-i;h=w,b=M}return[l*h,f*b]}function rf(e,n){if(e===0n)return 0n;if(e<0n)return-rf(-e,n);let t=BigInt(n),i=1n<<t,o=nd(n)/2n;if(e>i){let d=(i<<t)/e;return o-rf(d,n)}let s=4n*i/10n,u=0,a=e;for(;a>s;){let d=a*a,g=(i<<t)+d>>t,h=td(g,n);a=(a<<t)/(i+h),u++}let l=a,f=a,c=a*a,p=2n*t;for(let d=3;f=f*c>>p,f!==0n;d+=2)d%4===3?l-=f/BigInt(d):l+=f/BigInt(d);for(let d=0;d<u;d++)l=2n*l;return l}var Xb=NaN,E=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<=ia.length)e._piFullPrecision===null&&(e._piFullPrecision=new e(ia[0]+"."+ia.slice(1))),i=e._piFullPrecision.toPrecision(t);else{let r=t+4;i=Be(RS(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=Q7(n);return e._eulerGammaCache=t,e._eulerGammaCachePrecision=n,t}significand;exponent;_digits;digitCount(){return this._digits??(this._digits=ra(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]=od(n,0);return}if(typeof n=="number"){[this.significand,this.exponent]=X7(n);return}[this.significand,this.exponent]=LS(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 Xb;let d=this.exponent;if(Number.isNaN(d))return Xb;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*$e(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 Xb;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(),u=n.digitCount(),a=s+t,l=u+i;if(a!==l){let d=r>0n?1:-1;return a>l?d:-d}let f=r,c=o,p=Math.abs(t-i);if(p>1e3){let d=s,g=u,h=Math.max(d,g)+1;d<h&&(f=f*$e(h-d)),g<h&&(c=c*$e(h-g))}else t<i?c=c*$e(p):f=f*$e(p);return f<c?-1:f>c?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*$e(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 Be(this.significand+n.significand,t);let s=t-i;return s>0?Be(this.significand*$e(s)+n.significand,i):Be(this.significand+n.significand*$e(-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 Be(this.significand-n.significand,t);let s=t-i;return s>0?Be(this.significand*$e(s)-n.significand,i):Be(this.significand-n.significand*$e(-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 Be(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 u=o*s,a=i+r,l=this.digitCount()+n.digitCount()-1,c=(u<0n?-u:u)>=$e(l)?l+1:l;return c<=t?Be(u,a):PS(u,a).roundToPrecKnownDigits(t,c)}return this.mul(n).toPrecision(t)}neg(){let n=this.significand;return n===0n?this:Number.isFinite(this.exponent)?Be(-n,this.exponent):n>0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY}abs(){return this.significand>=0n?this:Number.isFinite(this.exponent)?Be(-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(Be(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(Be(1n,0)):t}return this}round(){let n=this.exponent;if(n>=0)return this;if(Number.isFinite(n)){let t=Be(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/$e(-n);return Be(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 Be(0n,0);let a=e.precision,l=10,f=this.digitCount(),c=n.digitCount(),p=a+l+Math.max(0,c-f),d=$e(p),g=r*d/o,h=t-i-p,b=g<0n?-g:g,y=f+p-c,x=b>=$e(y)?y+1:y;return PS(g,h).roundToPrecKnownDigits(a,x)}if(t!==t||i!==i)return e.NAN;let s=!Number.isFinite(t),u=!Number.isFinite(i);if(s&&u)return e.NAN;if(s){let a=r>0n?1n:-1n,l=o>0n?1n:o<0n?-1n:1n;return a*l>0n?e.POSITIVE_INFINITY:e.NEGATIVE_INFINITY}return Be(0n,0)}inv(){return Be(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 u=o<0n!=s<0n,a=o<0n?-o:o,l=s<0n?-s:s,f=e.precision,p=f+10+Math.max(0,n.digitCount()-this.digitCount()),d=a*$e(p),g=d/l,h=d%l!==0n,b=i-r-p,y=this.digitCount()+p-n.digitCount(),x=g>=$e(y)?y+1:y,v=u?t==="floor":t==="ceiling",[S,_]=DS(g,h,b,f,v,x);return Be(u?-S:S,_)}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,u=Math.floor(s/2),a=t+i-u;o+2*a<0&&(a=Math.ceil(-o/2)+1);let l=o+2*a,f=l>=0?r*$e(l):r/$e(-l),c=of(f),p=c*c!==f,[d,g]=DS(c,p,-a,t,n==="ceiling");return Be(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 Be(0n,0);let r=t-i,o=r>=0?this.significand*$e(r):this.significand,s=r>=0?n.significand:n.significand*$e(-r),u=o/s;return this.sub(Be(u,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 u=n.toBigInt();if(u===0n)return Be(1n,0);if(!this.isFinite())return u>0n?this.significand<0n&&u%2n!==0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY:Be(0n,0);if(this.isZero())return u>0n?Be(0n,0):e.POSITIVE_INFINITY;if(u<0n)return this.pow(n.neg()).inv();let a=this.significand<0n?-this.significand:this.significand,l=this.digitCount(),f=l>15?l-15:0,c=f>0?Number(a/10n**BigInt(f)):Number(a),p=Math.log10(c)+f+this.exponent,d=Number(u)*p;if(d>9e15)return this.significand<0n&&u%2n!==0n?e.NEGATIVE_INFINITY:e.POSITIVE_INFINITY;if(d<-9e15)return Be(0n,0);let g=e.precision,h=u.toString(2).length,b=Math.min(2*h+5,100),y=g+b,x=Be(1n,0),v=this,S=u;for(;S>0n;)S&1n&&(x=x.mulToPrecision(v,y)),S>>=1n,S>0n&&(v=v.mulToPrecision(v,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 u=W7(this,s+o);return n.mul(u).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 a=i===1?t:t[0]+"."+t.slice(1),l=r>=0?"+":"";return`${o}${a}e${l}${r}`}if(this.exponent>=0)return o+t+"0".repeat(this.exponent);let s=-this.exponent;if(s<i){let a=t.slice(0,i-s),l=t.slice(i-s);return`${o}${a}.${l}`}let u=s-i;return`${o}0.${"0".repeat(u)}${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,u;if(o>=0)u=r===0n,s=u?"0":r.toString()+"0".repeat(o);else{let c=$e(-o),p=r/c,d=r%c,g=c/2n,h;d>g?h=p+1n:d<g||c%2n!==0n||p%2n===0n?h=p:h=p+1n,u=h===0n,s=h.toString()}let a=i&&!u?"-":"";if(t===0)return`${a}${s}`;if(s.length<=t){let c=s.padStart(t,"0");return`${a}0.${c}`}let l=s.slice(0,s.length-t),f=s.slice(s.length-t);return`${a}${l}.${f}`}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=$e(r),s=i/o,u=i-s*o,a=o/2n;(u>a||u===a&&s%2n!==0n)&&(s+=1n);let l=this.significand<0n?-s:s;return Be(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*$e(this.exponent);let n=$e(-this.exponent);return this.significand/n}},Y7=8,sf=[];function W7(e,n){let t=e.significand,i=e.exponent;for(let o=sf.length-1;o>=0;o--){let s=sf[o];if(s.prec===n&&s.exp===i&&s.sig===t)return s.ln}let r=e.ln();return sf.push({sig:t,exp:i,prec:n,ln:r}),sf.length>Y7&&sf.shift(),r}function Q7(e){let n=e+20+Math.ceil(Math.log10(e+10)),t=E.precision;E.precision=n;try{let i=Math.ceil(n*Math.LN10/4)+5,r=new E(i),o=r.mul(r),s=E.ONE,u=E.ONE,a=E.ZERO,l=E.ZERO,f=E.ONE.div(new E(10).pow(n)),c=6*i+100;for(let p=1;p<=c;p++){let d=new E(p).mul(p);if(s=s.mul(o).div(d).toPrecision(n),l=l.add(E.ONE.div(p)).toPrecision(n),u=u.add(s).toPrecision(n),a=a.add(s.mul(l)).toPrecision(n),p>i&&s.lt(u.mul(f)))break}return a.div(u).sub(r.ln()).toPrecision(e)}finally{E.precision=t}}function Be(e,n){let[t,i]=od(e,n),r=Object.create(E.prototype);return r.significand=t,r.exponent=i,r}function PS(e,n){let t=Object.create(E.prototype);return t.significand=e,t.exponent=n,t}function DS(e,n,t,i,r,o){if(e===0n)return[r&&n?1n:0n,t];let s=o??ra(e);if(s<=i)return[r&&n?e+1n:e,t];let u=s-i,a=$e(u),l=e/a,f=n||e%a!==0n;return r&&f&&(l+=1n),[l,t+u]}var OS=1000000000n,FS=1000n;function od(e,n){if(e===0n)return[0n,0];if((e&1n)!==0n)return[e,n];if(e%10n!==0n)return[e,n];for(;e%OS===0n;)e/=OS,n+=9;for(;e%FS===0n;)e/=FS,n+=3;for(;e%10n===0n;)e/=10n,n+=1;return[e,n]}function X7(e){return Number.isNaN(e)?[0n,NaN]:e===1/0?[1n,1/0]:e===-1/0?[-1n,1/0]:Number.isInteger(e)?od(BigInt(e),0):LS(e.toString())}function LS(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,u;o===-1?(s=n,u=""):(s=n.slice(0,o),u=n.slice(o+1)),s=s.replace(/^0+/,"")||"0";let a=s+u;if(a.length===0||!/^\d+$/.test(a))return[0n,NaN];let l=BigInt(a);r&&(l=-l);let f=-u.length;return od(l,f+t)}var K7=Math.log2(10),qS=Math.log10(2),e9=16,e0=1e6;function fo(e,n){let t=Math.ceil(n*K7)+e9,i=BigInt(t);return e.exponent>=0?[e.significand*$e(e.exponent)<<i,t]:[(e.significand<<i)/$e(-e.exponent),t]}function co(e,n,t){if(e===0n)return E.ZERO;let i=e<0n,r=i?-e:e,o=BigInt(n),s=lo(r)-n,u=Math.floor(s*qS),a=t+4-u,l,f;if(a>=0)l=r*$e(a)+(1n<<o-1n)>>o,f=-a;else{let p=$e(-a)<<o;l=(r+p/2n)/p,f=-a}if(l===0n)return E.ZERO;let c=ra(l);if(c>t){let p=c-t,d=$e(p),g=d/2n,h=l%d;l=l/d,h>=g&&(l+=1n),f+=p}return Be(i?-l:l,f)}function Dt(e){return e.exponent+e.digitCount()-1}function Kb(e,n){if(e===0n)return 0;let t=e<0n?-e:e,i=n*qS-(ra(t)-1);return i>0?Math.ceil(i):0}var VS=5,$S=BigInt(Number.MAX_SAFE_INTEGER),Xs=null;function jS(e){if(Xs!==null){if(Xs.bits===e)return Xs.value;if(Xs.bits>e)return Xs.value>>BigInt(Xs.bits-e)}let n=Qb(10n<<BigInt(e),e);return Xs={bits:e,value:n},n}E.prototype.sqrt=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NAN;if(this.significand<0n)return E.NAN;let e=E.precision,n=e+10,t=Dt(this),i=Math.floor(t/2),r=Be(this.significand,this.exponent-2*i),[o,s]=fo(r,n),u=td(o,s),a=co(u,s,e);return Be(a.significand,a.exponent+i)};E.prototype.cbrt=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NEGATIVE_INFINITY;if(this.significand<0n)return this.neg().cbrt().neg();let e=E.precision,n=e+10,t=Dt(this),i=Math.floor(t/3),r=Be(this.significand,this.exponent-3*i),[o,s]=fo(r,n),u=o<<BigInt(2*s),a,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?(a=BigInt(Math.floor(d*p)),a===0n&&(a=1n)):a=BS(u)}else a=BS(u);let f;do{f=a;let p=a*a;if(p===0n){a=1n;break}a=(2n*a+u/p)/3n}while(Ci(a-f)>1n);{let p=(2n*a+u/(a*a))/3n,d=Ci(a*a*a-u);Ci(p*p*p-u)<d&&(a=p)}let c=co(a,s,e);return Be(c.significand,c.exponent+i)};E.sqrt=function(e){return e.sqrt()};E.cbrt=function(e){return e.cbrt()};E.prototype.exp=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.ZERO;if(this.isZero())return E.ONE;if(Dt(this)>=17)return this.significand>0n?E.POSITIVE_INFINITY:E.ZERO;let e=E.precision,n=Math.max(0,this.exponent+this.digitCount()),t=e+20+n,[i,r]=fo(this,t),o=jS(r),s=i/o,u=i-s*o;if(u<0n&&(s-=1n,u+=o),s>$S||s<-$S)return s>0n?E.POSITIVE_INFINITY:E.ZERO;let a=co(Wb(u,r),r,e),l=a.exponent+Number(s);return Number.isSafeInteger(l)?Be(a.significand,l):s>0n?E.POSITIVE_INFINITY:E.ZERO};E.prototype.ln=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NAN;if(this.isZero())return E.NEGATIVE_INFINITY;if(this.significand<0n)return E.NAN;if(this.eq(1))return E.ZERO;let e=E.precision,n=this.significand,t=this.digitCount(),i=this.exponent+t-1,r=Be(n,-(t-1)),o=Math.abs(i).toString().length,s=0;if(i===0||i===-1){let p=this.sub(E.ONE);if(!p.isZero()){let d=Dt(p);d<0&&(s=-d)}}let u=e+20+o+s,[a,l]=fo(r,u),f=jS(l),c=Qb(a,l)+BigInt(i)*f;return co(c,l,e)};E.prototype.log=function(e){let n=e instanceof E?e:new E(e),t=E.precision;E.precision=t+10;try{return this.ln().div(n.ln()).toPrecision(t)}finally{E.precision=t}};E.exp=function(e){return e.exp()};E.ln=function(e){return e.ln()};E.log10=function(e){return e.log(10)};E.log2=function(e){return e.log(2)};E.prototype.sin=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.isZero())return E.ZERO;let e=E.precision,n=Dt(this);if(n<0&&-2*n>=e+4)return this.toPrecision(e);let t=e+15+(n<0?-n:0);if(n+t+30>e0)return E.NAN;let[i,r]=fo(this,t),[o]=rd(i,r);return co(o,r,e)};E.prototype.cos=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.isZero())return E.ONE;let e=E.precision,n=Dt(this),t=0;for(let i=0;;i++){let r=e+15+t;if(n+r+30>e0)return E.NAN;let[o,s]=fo(this,r),[,u]=rd(o,s);if(u===0n){if(i>=3)return E.ZERO;t+=e+30;continue}let a=Kb(u,s);if(a<=t+VS||i>=3)return co(u,s,e);t=a+5}};E.prototype.tan=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.isZero())return E.ZERO;let e=E.precision,n=Dt(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>e0)return E.NAN;let[s,u]=fo(this,o),[a,l]=rd(s,u);if(l===0n){if(r>=3)return a>0n?E.POSITIVE_INFINITY:E.NEGATIVE_INFINITY;i+=e+30;continue}let f=Math.max(a===0n?0:Kb(a,u),Kb(l,u));if(f<=i+VS||r>=3){let c=(a<<BigInt(u))/l;return co(c,u,e)}i=f+5}};E.prototype.atan=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite()){let s=E.PI.div(E.TWO);return this.significand>0n?s:s.neg()}let e=E.precision,n=Dt(this);if(n<0&&-2*n>=e+4)return this.toPrecision(e);let t=e+15+(n<0?-n:0),[i,r]=fo(this,t),o=rf(i,r);return co(o,r,e)};E.prototype.asin=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.isZero())return E.ZERO;let e=this.abs(),n=E.ONE;if(e.gt(n))return E.NAN;if(e.eq(n)){let d=E.PI.div(E.TWO);return this.significand>0n?d:d.neg()}let t=E.precision,i=Dt(this);if(i<0&&-2*i>=t+4)return this.toPrecision(t);let r=t+20+(i<0?-i:0),[o,s]=fo(this,r),u=1n<<BigInt(s),a=MS(o,o,s),l=u-a,f=td(l,s),c=CS(o,f,s),p=rf(c,s);return co(p,s,t)};E.prototype.acos=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.abs().gt(E.ONE))return E.NAN;if(this.eq(1))return E.ZERO;if(this.eq(-1))return E.PI;let n=E.precision,t=E.precision;E.precision=n+10;try{let i=E.TWO;if(this.significand>=0n){let o=E.ONE.sub(this).mulToPrecision(E.HALF,n+10).sqrt();return i.mulToPrecision(o.asin(),n)}let r=E.ONE.add(this).mulToPrecision(E.HALF,n+10).sqrt();return E.PI.sub(i.mul(r.asin())).toPrecision(n)}finally{E.precision=t}};E.sin=function(e){return e.sin()};E.cos=function(e){return e.cos()};E.tan=function(e){return e.tan()};E.asin=function(e){return e.asin()};E.acos=function(e){return e.acos()};E.atan=function(e){return e.atan()};E.atan2=function(e,n){let t=e instanceof E?e:new E(e);if(t.isNaN()||n.isNaN())return E.NAN;let i=E.PI,r=i.div(E.TWO);if(n.isZero())return t.isZero()?E.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)};E.prototype.sinh=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NEGATIVE_INFINITY;let e=E.precision,n=Dt(this);if(n<0){if(-2*n>=e+4)return this.toPrecision(e);let r=E.precision;E.precision=e-n+5;try{let o=this.exp();return o.sub(o.inv()).mulToPrecision(E.HALF,e)}finally{E.precision=r}}if(Math.abs(this.toNumber())>1.16*(e+3)){let r=this.abs().exp().div(E.TWO);return this.significand>0n?r:r.neg()}let t=this.exp(),i=t.inv();return t.sub(i).div(E.TWO)};E.prototype.cosh=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ONE;if(!this.isFinite())return E.POSITIVE_INFINITY;let e=E.precision;if(Math.abs(this.toNumber())>1.16*(e+3))return this.abs().exp().div(E.TWO);let n=this.exp(),t=n.inv();return n.add(t).div(E.TWO)};E.prototype.tanh=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite())return this.significand>0n?E.ONE:E.NEGATIVE_ONE;let e=E.precision,n=Dt(this);if(n<0){if(-2*n>=e+4)return this.toPrecision(e);let i=E.precision;E.precision=e-n+5;try{let r=this.mul(E.TWO).exp();return r.sub(E.ONE).div(r.add(E.ONE)).toPrecision(e)}finally{E.precision=i}}if(Math.abs(this.toNumber())>1.16*(e+3))return this.significand>0n?E.ONE:E.NEGATIVE_ONE;let t=this.mul(E.TWO).exp();return t.sub(E.ONE).div(t.add(E.ONE))};E.sinh=function(e){return e.sinh()};E.cosh=function(e){return e.cosh()};E.tanh=function(e){return e.tanh()};E.prototype.expm1=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NEGATIVE_ONE;if(this.isZero())return E.ZERO;let e=E.precision,n=Dt(this);if(n<0&&-n>=e+2)return this.toPrecision(e);if(n<0){let t=E.precision;E.precision=e-n+5;try{return this.exp().sub(E.ONE).toPrecision(e)}finally{E.precision=t}}return this.exp().sub(E.ONE)};E.prototype.log1p=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NAN;if(this.isZero())return E.ZERO;let e=E.ONE.add(this);if(e.isZero())return E.NEGATIVE_INFINITY;if(e.significand<0n)return E.NAN;let n=E.precision,t=Dt(this);if(t<0&&-t>=n+2)return this.toPrecision(n);if(t<0){let i=E.precision;E.precision=n-t+5;try{return E.ONE.add(this).ln().toPrecision(n)}finally{E.precision=i}}return E.ONE.add(this).ln()};E.prototype.asinh=function(){if(this.isNaN())return E.NAN;if(this.isZero())return E.ZERO;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NEGATIVE_INFINITY;let e=this.significand<0n,n=this.abs(),t=E.precision,i=Dt(this);if(i<0&&-2*i>=t+4)return this.toPrecision(t);let r=()=>n.add(n.mul(n).add(E.ONE).sqrt()).ln(),o;if(i<0){let s=E.precision;E.precision=t-i+5;try{o=r().toPrecision(t)}finally{E.precision=s}}else o=r();return e?o.neg():o};E.prototype.acosh=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:E.NAN;if(this.lt(E.ONE))return E.NAN;if(this.eq(1))return E.ZERO;let e=this.sub(E.ONE).div(E.TWO).sqrt();return E.TWO.mul(e.asinh())};E.prototype.atanh=function(){if(this.isNaN())return E.NAN;if(!this.isFinite())return E.NAN;if(this.isZero())return E.ZERO;let e=this.abs();if(e.eq(1))return this.significand>0n?E.POSITIVE_INFINITY:E.NEGATIVE_INFINITY;if(e.gt(E.ONE))return E.NAN;let n=E.precision,t=Dt(this);if(-2*t>=n+4)return this.toPrecision(n);let i=E.precision;E.precision=n-t+5;try{return E.ONE.add(this).div(E.ONE.sub(this)).ln().mulToPrecision(E.HALF,n)}finally{E.precision=i}};E.prototype.nthRoot=function(e){if(this.isNaN()||!Number.isInteger(e)||e===0)return E.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 E.ZERO;if(!this.isFinite())return this.significand>0n?E.POSITIVE_INFINITY:e%2===0?E.NAN:E.NEGATIVE_INFINITY;if(this.significand<0n)return e%2===0?E.NAN:this.neg().nthRoot(e).neg();let n=E.precision,t=E.precision;E.precision=n+8;try{return E.exp(this.ln().div(new E(e))).toPrecision(n)}finally{E.precision=t}};E.asinh=function(e){return e.asinh()};E.acosh=function(e){return e.acosh()};E.atanh=function(e){return e.atanh()};E.expm1=function(e){return e.expm1()};E.log1p=function(e){return e.log1p()};E.nthRoot=function(e,n){return e.nthRoot(n)};function BS(e){let n=lo(e);if(n<=1023){let a=Math.cbrt(Number(e));if(Number.isFinite(a)&&a>=1)return BigInt(Math.floor(a))}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 u=BigInt(Math.round(r))<<BigInt(o);return u>0n?u:1n}var oa=["number","finite_number","complex","finite_complex","imaginary","real","finite_real","rational","finite_rational","integer","finite_integer","non_finite_number"],n0=["indexed_collection","list","tuple"],sd=[...n0,"collection","set","record","dictionary"],ud=["scalar",...oa,"boolean","string"],t0=["value","color",...sd,...ud],i0=["expression","symbol","function",...t0],r0=["any","unknown","nothing","never","error",...i0],sa=new Set(oa),zS=new Set(sd),JS=new Set(ud),Ks=new Set(r0);function GS(e){return typeof e!="string"?!1:Ks.has(e)}function po(e){return typeof e=="string"?Ks.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 ad=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)?E.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=Pc(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=Vt(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=uM(e);if(t!==void 0)return t}return CA(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})=>CA(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",$i(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",$i(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})=>Og(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})=>Og(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=>Ze(e),evaluate:(e,{numericApproximation:n})=>MA(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=>Ze(e),evaluate:(e,{numericApproximation:n})=>MA(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=>Ze(e),evaluate:([e,n,t],{numericApproximation:i})=>{let r=Sx(e,n,!0,!1);if(r!==void 0)return Sx(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})=>Og(n,e,"Supremum")},Infimum:{description:"Like Min, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number | list",evaluate:(e,{engine:n})=>Og(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],u=n.ops[o];if(!N(s)||!N(u)||s.isFinite===!1||u.isFinite===!1)return t.error("expected-value");r.push(t.function("Power",[t.function("Subtract",[s,u]),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:yx,canonical:([e,...n],{scope:t})=>px("Product",e,n,t),evaluate:(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1),o=qc(e[0],r,t);if(o==="symbolic")return r.length===1?ux(e[0],r[0],t):void 0;if(o==="numeric"&&!i)return r.length===1?lx(e[0],r[0],t):void 0;if(o==="numeric"&&i&&r.length===1){let u=cx(e[0],r[0],t);if(u!==void 0)return u}let s=Et(jc(e[0],r,(u,a)=>{let l=a.evaluate({numericApproximation:i});return _x(u,l)??u.mul(l)},t.One),t._timeRemaining);if(s!==qo)return s?.evaluate({numericApproximation:i})??t.NaN},evaluateAsync:async(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1);{let s=qc(e[0],r,t);if(s==="symbolic")return r.length===1?ux(e[0],r[0],t):void 0;if(s==="numeric"&&!i)return r.length===1?lx(e[0],r[0],t):void 0;if(s==="numeric"&&i&&r.length===1){let u=cx(e[0],r[0],t);if(u!==void 0)return u}}let o=await eu(jc(e[0],r,(s,u)=>{let a=u.evaluate({numericApproximation:i});return _x(s,a)??s.mul(a)},t.One),t._timeRemaining,n.signal);if(o!==qo)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:yx,canonical:([e,...n],{scope:t,engine:i})=>{if(n.length===0){let r=e?.canonical;if(r?.isCollection)return i._fn("Sum",[r])}return px("Sum",e,n,t)},evaluate:([e,...n],{engine:t,numericApproximation:i})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Bo(e)?void 0:Et(TA(e,t.Zero,(a,l)=>Dg(a,l.evaluate({numericApproximation:i}),i)),t._timeRemaining)?.evaluate({numericApproximation:i})??t.NaN;let r=i,o=qc(e,n,t);if(o==="symbolic")return n.length===1?sx(e,n[0],t):void 0;if(o==="numeric"&&!r)return n.length===1?ax(e,n[0],t):void 0;if(o==="numeric"&&r&&n.length===1){let u=fx(e,n[0],t);if(u!==void 0)return u}let s=Et(jc(e,n,(u,a)=>Dg(u,a.evaluate({numericApproximation:r}),r),t.Zero),t._timeRemaining);if(s!==qo)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||Bo(e)?void 0:(await eu(TA(e,t.Zero,(a,l)=>Dg(a,l.evaluate({numericApproximation:r}),r)),t._timeRemaining,i))?.evaluate({numericApproximation:r})??t.NaN;let o=r;{let u=qc(e,n,t);if(u==="symbolic")return n.length===1?sx(e,n[0],t):void 0;if(u==="numeric"&&!o)return n.length===1?ax(e,n[0],t):void 0;if(u==="numeric"&&o&&n.length===1){let a=fx(e,n[0],t);if(a!==void 0)return a}}let s=await eu(jc(e,n,(u,a)=>Dg(u,a.evaluate({numericApproximation:o}),o),t.Zero),t._timeRemaining,i);if(s!==qo)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 Uc(e)??e}}}];function wA(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 _x(e,n){if(e.operator==="Error")return e;if(B(n))return e.engine.typeError("number",n.type)}function Dg(e,n,t){let i=_x(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*TA(e,n,t){let i=n;for(let r of e.each())i=t(i,r),yield i;return i}function jB(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=ml(e);if(s){let[u,a]=s,l=t.function("Add",[t.function("Multiply",[u,u]),t.function("Multiply",[a,a])]),f=Ae(l).evaluate();if(N(f)&&f.im===0&&f.isNonNegative===!0){let c=r*r+o*o,p=f.re;if(Number.isFinite(p)&&Math.abs(p-c)<=1e-10*(1+Math.abs(c)))return t.function("Sqrt",[f]).evaluate({numericApproximation:n})}}}}}function ml(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=ml(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=ml(e.op1);return i?[i[0].neg(),i[1].neg()]:void 0}if(t==="Subtract"){let i=ml(e.op1),r=ml(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=ml(o);if(!s)return;let[u,a]=s,l=n.function("Subtract",[n.function("Multiply",[i,u]),n.function("Multiply",[r,a])]),f=n.function("Add",[n.function("Multiply",[i,a]),n.function("Multiply",[r,u])]);i=l,r=f}return[i,r]}if(t==="Complex")return[e.op1,e.op2]}return[e,n.Zero]}function kA(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(jr(e))return[void 0,[e]];if(i){let r=Bi(e),o=UC(r);return[t.number(Math.max(r[0],o)),[]]}else return[t.number(Bi(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||Bo(e))return[void 0,[e]];let r,o=[];for(let s of e.each()){let[u,a]=kA(s,n);if(u){if(u.isNaN)return[t.NaN,[]];u.im!==0?o.push(u):r?(i&&u.isGreater(r)||!i&&u.isLess(r))&&(r=u):r=u}o.push(...a)}return[r,o]}return!e.isNumber||!N(e)?[void 0,[e]]:[e,[]]}function Sx(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 MA(e,n,t){if(e.length===0)return;let i=e[0];for(let r=1;r<e.length;r++){let o=Sx(i,e[r],n,!1);if(o===void 0)return;i=o}return t?i.N():i}function Og(e,n,t){let i=t==="Max"||t==="Supremum";if(n=Ne(n),n.length===0)return i?e.NegativeInfinity:e.PositiveInfinity;let r,o=[];for(let s of n){let[u,a]=kA(s,t);if(u){if(u.isNaN)return e.NaN;u.im!==0?o.push(u):r?(i&&u.isGreater(r)||!i&&u.isLess(r))&&(r=u):r=u}o.push(...a)}return o.length>0?e.expr(r?[t,r,...o]:[t,...o]):r??(i?e.NegativeInfinity:e.PositiveInfinity)}function CA(e,n,t){let i=t==="LCM"?nu:Dn,r=t==="LCM"?zT:Uy;if(n.length===0)return t==="LCM"?e.One:e.Zero;if(n.some(u=>u.isCollection)){let u=!0,a=[...n];for(;u&&a.some(l=>l.isCollection);){let l=[];for(let f of a)if(f.isCollection){if(f.isFiniteCollection!==!0||Bo(f)){u=!1;break}for(let c of f.each())l.push(c)}else l.push(f);u&&(a=l)}if(u){if(a.length===0)return t==="LCM"?e.One:e.Zero;n=a}}if(n.length>0&&n.some(u=>N(u)&&!u.isExact)&&n.every(u=>N(u)&&Number.isFinite(u.re)&&!u.im)){let u=t==="LCM"?md:cf,a=Math.abs(n[0].re);for(let l=1;l<n.length;l++)a=u(a,n[l].re);return e.number(a)}let o=[];if(en(e)){let u=null;for(let a of n)if(u===null){let l=By(a);l!==null&&l.isInteger()?u=l.abs():o.push(a)}else{let l=By(a);l&&l.isInteger()?u=r(u,l):o.push(a)}return o.length===0?u===null?e.One:e.number(u):u===null?e._fn(t,o):e._fn(t,[e.number(u),...o])}let s=null;for(let u of n)s===null?u.isInteger?s=Math.abs(u.re):o.push(u):u.isInteger?s=i(s,u.re):o.push(u);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 zB=new Set(["Negate","Add","Subtract","Multiply","Divide","Square","Exp","Power"]),JB=new Map([["Multiply",["Divide"]],["Divide",["Power"]],["Root",["Power"]]]),GB=8,RA=new WeakMap;function Nx(e,n,t=GB){if(e.length<t)return;let i=RA.get(e);return(i===void 0||i.count!==e.length)&&(i={count:e.length},RA.set(e,i)),n?i.variations??=PA(e,!0):i.plain??=PA(e,!1)}function PA(e,n){let t=new Map,i=[],r=(o,s)=>{let u=t.get(o);u?u.push(s):t.set(o,[s])};for(let o=0;o<e.length;o++){let s=e[o],u={rule:s,ordinal:o};if(s.operators!==void 0&&s.operators.length>0){for(let c of s.operators)r(c,u);continue}let a=s.match;if(a===void 0){i.push(u);continue}if(!m(a)){i.push(u);continue}let l=a.operator;if(l.startsWith("_")){i.push(u);continue}if((s.useVariations??n)&&zB.has(l)){i.push(u);continue}r(l,u)}return{byHead:t,alwaysTry:i,count:e.length}}function UB(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*Fg(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=JB.get(r);if(s!==void 0)for(let l of s){let f=e.byHead.get(l);f!==void 0&&i.push(f)}if(N(n)){let l=e.byHead.get("Divide");l!==void 0&&i.push(l)}let u=i.map(l=>UB(l,t)),a=-1;for(;;){let l=-1,f=1/0;for(let p=0;p<i.length;p++)if(u[p]<i[p].length){let d=i[p][u[p]].ordinal;d<f&&(f=d,l=p)}if(l<0)return;let c=i[l][u[l]++];c.ordinal!==a&&(a=c.ordinal,yield c)}}function DA(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 ZB={};function HB(e,n){let t=n.map(o=>o.replace),i=t.length;return{_tag:"boxed-rule",match:void 0,replace:o=>{let s=o,u;for(let a=0;a<i;a++){let l=t[a](s,ZB);if(l!=null&&"because"in l){let f=l;s=f.value,u=f}}return u},condition:void 0,operators:[e],id:`hot-head-dispatch:${e}`}}function OA(e){let n=new Map;for(let o of e){if(!DA(o))continue;let s=o.operators[0],u=n.get(s);u?u.push(o):n.set(s,[o])}let t=new Map;for(let[o,s]of n)s.length>=2&&t.set(o,HB(o,s));if(t.size===0)return e;let i=new Set,r=[];for(let o of e){if(DA(o)){let s=o.operators[0],u=t.get(s);if(u!==void 0){i.has(s)||(i.add(s),r.push(u));continue}}r.push(o)}return r}var FA=new WeakSet;var VA={boolean:e=>e.type.matches("boolean"),string:e=>B(e),number:e=>N(e),symbol:e=>I(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=>Pc(e)===!0,composite:e=>e.isInteger===!0&&e.isPositive===!0&&e.isEqual(1)===!1&&Pc(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=>dt(e.operator),equation:e=>e.operator==="Equal",inequality:e=>Xi(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 jA(e,n){for(let t of n)if(VA[t](e)!==!0)return!1;return!0}function zA(e,n){let t=e._isVerifying;e._isVerifying=!0;try{return I(n.evaluate(),"True")}finally{e._isVerifying=t}}function YB(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 WB(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(YB(r))){t=i[r];break}}if(!t)return null;for(let i of t.split(","))if(!Object.keys(VA).includes(i))throw new Error(`Unexpected condition "${i}" in a rule`);return t}function LA(e){let n=[];do{let t=WB(e);if(!t)break;n.push(t)}while(e.match(","));return n.join(",")}function Ix(e){let n=null;if(e.match(":"))n=LA(e);else if(e.matchAll(["_","<{>"])&&(n=LA(e),!e.match("<}>")))return null;return n}function QB(e){return I(e,"e")?e.engine.symbol("ExponentialE",{canonical:!1}):I(e,"i")?e.engine.I:e}function Lg(e){return e.map(QB,{canonical:!1})}function XB(e){if(m(e,"InvisibleOperator")&&I(e.ops[0],"_")){let n=e.ops.slice(1);if(n.length>0&&n.every(t=>I(t)))return e.engine.symbol("_"+n.map(t=>t.symbol).join(""))}return m(e,"Subscript")&&I(e.op1,"_")&&I(e.op2)?e.engine.symbol("__"+e.op2.symbol):e}function $A(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=Lg(r),r=r.map(XB,{canonical:!1}),t?.autoWildcard&&(r=r.map(o=>I(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 KB(e,n,t){let i=p=>({kind:"symbol",latexTrigger:p,parse:(d,g)=>{r[p]||(r[p]=`_${p}`);let h=Ix(d);return h!==null&&(o[p]?o[p]+=","+h:o[p]=h),r[p]}}),r={},o={},s=[...em,{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=Ix(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 v=!1,S=p.index;do{p.skipSpace();let _=p.nextToken();if(r[_]){let w=Ix(p);if(w===null||!w){v=!0,p.index=S;break}o[_]?o[_]+=","+w:o[_]=w}}while(!v&&!p.atEnd);b=p.parseExpression(g)}let y=[];for(let v in o){let S=o[v].split(",");S.length!==0&&(S.length===1?y.push(["Condition",r[v],S[0]]):y.push(["Condition",r[v],["And",...S]]))}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]}}],u=t?.canonical??!1,a=e._requireLatexSyntax().constructor,l=new a({dictionary:s}),f=e.contextStack[0]?.lexicalScope;f&&e.pushScope({parent:f,bindings:new Map});let c;try{if(c=e.expr(l.parse(n)??"Nothing"),!c.isValid||c.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)?E.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=Pc(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=Vt(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=uM(e);if(t!==void 0)return t}return CA(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})=>CA(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",$i(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",$i(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})=>Og(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})=>Og(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=>Ze(e),evaluate:(e,{numericApproximation:n})=>MA(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=>Ze(e),evaluate:(e,{numericApproximation:n})=>MA(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=>Ze(e),evaluate:([e,n,t],{numericApproximation:i})=>{let r=Sx(e,n,!0,!1);if(r!==void 0)return Sx(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})=>Og(n,e,"Supremum")},Infimum:{description:"Like Min, but defined for open sets",complexity:1200,broadcastable:!1,signature:"(value*) -> number",evaluate:(e,{engine:n})=>Og(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],u=n.ops[o];if(!N(s)||!N(u)||s.isFinite===!1||u.isFinite===!1)return t.error("expected-value");r.push(t.function("Power",[t.function("Subtract",[s,u]),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:yx,canonical:([e,...n],{scope:t})=>px("Product",e,n,t),evaluate:(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1),o=qc(e[0],r,t);if(o==="symbolic")return r.length===1?ux(e[0],r[0],t):void 0;if(o==="numeric"&&!i)return r.length===1?lx(e[0],r[0],t):void 0;if(o==="numeric"&&i&&r.length===1){let u=cx(e[0],r[0],t);if(u!==void 0)return u}let s=Et(jc(e[0],r,(u,a)=>{let l=a.evaluate({numericApproximation:i});return _x(u,l)??u.mul(l)},t.One),t._timeRemaining);if(s!==qo)return s?.evaluate({numericApproximation:i})??t.NaN},evaluateAsync:async(e,n)=>{let t=n.engine,i=n.numericApproximation,r=e.slice(1);{let s=qc(e[0],r,t);if(s==="symbolic")return r.length===1?ux(e[0],r[0],t):void 0;if(s==="numeric"&&!i)return r.length===1?lx(e[0],r[0],t):void 0;if(s==="numeric"&&i&&r.length===1){let u=cx(e[0],r[0],t);if(u!==void 0)return u}}let o=await eu(jc(e[0],r,(s,u)=>{let a=u.evaluate({numericApproximation:i});return _x(s,a)??s.mul(a)},t.One),t._timeRemaining,n.signal);if(o!==qo)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:yx,canonical:([e,...n],{scope:t,engine:i})=>{if(n.length===0){let r=e?.canonical;if(r?.isCollection)return i._fn("Sum",[r])}return px("Sum",e,n,t)},evaluate:([e,...n],{engine:t,numericApproximation:i})=>{if(n.length===0&&e?.isCollection)return e.isFiniteCollection!==!0||Bo(e)?void 0:Et(TA(e,t.Zero,(a,l)=>Dg(a,l.evaluate({numericApproximation:i}),i)),t._timeRemaining)?.evaluate({numericApproximation:i})??t.NaN;let r=i,o=qc(e,n,t);if(o==="symbolic")return n.length===1?sx(e,n[0],t):void 0;if(o==="numeric"&&!r)return n.length===1?ax(e,n[0],t):void 0;if(o==="numeric"&&r&&n.length===1){let u=fx(e,n[0],t);if(u!==void 0)return u}let s=Et(jc(e,n,(u,a)=>Dg(u,a.evaluate({numericApproximation:r}),r),t.Zero),t._timeRemaining);if(s!==qo)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||Bo(e)?void 0:(await eu(TA(e,t.Zero,(a,l)=>Dg(a,l.evaluate({numericApproximation:r}),r)),t._timeRemaining,i))?.evaluate({numericApproximation:r})??t.NaN;let o=r;{let u=qc(e,n,t);if(u==="symbolic")return n.length===1?sx(e,n[0],t):void 0;if(u==="numeric"&&!o)return n.length===1?ax(e,n[0],t):void 0;if(u==="numeric"&&o&&n.length===1){let a=fx(e,n[0],t);if(a!==void 0)return a}}let s=await eu(jc(e,n,(u,a)=>Dg(u,a.evaluate({numericApproximation:o}),o),t.Zero),t._timeRemaining,i);if(s!==qo)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 Uc(e)??e}}}];function wA(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 _x(e,n){if(e.operator==="Error")return e;if(B(n))return e.engine.typeError("number",n.type)}function Dg(e,n,t){let i=_x(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*TA(e,n,t){let i=n;for(let r of e.each())i=t(i,r),yield i;return i}function jB(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=ml(e);if(s){let[u,a]=s,l=t.function("Add",[t.function("Multiply",[u,u]),t.function("Multiply",[a,a])]),f=Ae(l).evaluate();if(N(f)&&f.im===0&&f.isNonNegative===!0){let c=r*r+o*o,p=f.re;if(Number.isFinite(p)&&Math.abs(p-c)<=1e-10*(1+Math.abs(c)))return t.function("Sqrt",[f]).evaluate({numericApproximation:n})}}}}}function ml(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=ml(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=ml(e.op1);return i?[i[0].neg(),i[1].neg()]:void 0}if(t==="Subtract"){let i=ml(e.op1),r=ml(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=ml(o);if(!s)return;let[u,a]=s,l=n.function("Subtract",[n.function("Multiply",[i,u]),n.function("Multiply",[r,a])]),f=n.function("Add",[n.function("Multiply",[i,a]),n.function("Multiply",[r,u])]);i=l,r=f}return[i,r]}if(t==="Complex")return[e.op1,e.op2]}return[e,n.Zero]}function kA(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(jr(e))return[void 0,[e]];if(i){let r=Bi(e),o=UC(r);return[t.number(Math.max(r[0],o)),[]]}else return[t.number(Bi(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||Bo(e))return[void 0,[e]];let r,o=[];for(let s of e.each()){let[u,a]=kA(s,n);if(u){if(u.isNaN)return[t.NaN,[]];u.im!==0?o.push(u):r?(i&&u.isGreater(r)||!i&&u.isLess(r))&&(r=u):r=u}o.push(...a)}return[r,o]}return!e.isNumber||!N(e)?[void 0,[e]]:[e,[]]}function Sx(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 MA(e,n,t){if(e.length===0)return;let i=e[0];for(let r=1;r<e.length;r++){let o=Sx(i,e[r],n,!1);if(o===void 0)return;i=o}return t?i.N():i}function Og(e,n,t){let i=t==="Max"||t==="Supremum";if(n=Ne(n),n.length===0)return i?e.NegativeInfinity:e.PositiveInfinity;let r,o=[];for(let s of n){let[u,a]=kA(s,t);if(u){if(u.isNaN)return e.NaN;u.im!==0?o.push(u):r?(i&&u.isGreater(r)||!i&&u.isLess(r))&&(r=u):r=u}o.push(...a)}return o.length>0?e.expr(r?[t,r,...o]:[t,...o]):r??(i?e.NegativeInfinity:e.PositiveInfinity)}function CA(e,n,t){let i=t==="LCM"?nu:Dn,r=t==="LCM"?zT:Uy;if(n.length===0)return t==="LCM"?e.One:e.Zero;if(n.some(u=>u.isCollection)){let u=!0,a=[...n];for(;u&&a.some(l=>l.isCollection);){let l=[];for(let f of a)if(f.isCollection){if(f.isFiniteCollection!==!0||Bo(f)){u=!1;break}for(let c of f.each())l.push(c)}else l.push(f);u&&(a=l)}if(u){if(a.length===0)return t==="LCM"?e.One:e.Zero;n=a}}if(n.length>0&&n.some(u=>N(u)&&!u.isExact)&&n.every(u=>N(u)&&Number.isFinite(u.re)&&!u.im)){let u=t==="LCM"?md:cf,a=Math.abs(n[0].re);for(let l=1;l<n.length;l++)a=u(a,n[l].re);return e.number(a)}let o=[];if(en(e)){let u=null;for(let a of n)if(u===null){let l=By(a);l!==null&&l.isInteger()?u=l.abs():o.push(a)}else{let l=By(a);l&&l.isInteger()?u=r(u,l):o.push(a)}return o.length===0?u===null?e.One:e.number(u):u===null?e._fn(t,o):e._fn(t,[e.number(u),...o])}let s=null;for(let u of n)s===null?u.isInteger?s=Math.abs(u.re):o.push(u):u.isInteger?s=i(s,u.re):o.push(u);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 zB=new Set(["Negate","Add","Subtract","Multiply","Divide","Square","Exp","Power"]),JB=new Map([["Multiply",["Divide"]],["Divide",["Power"]],["Root",["Power"]]]),GB=8,RA=new WeakMap;function Nx(e,n,t=GB){if(e.length<t)return;let i=RA.get(e);return(i===void 0||i.count!==e.length)&&(i={count:e.length},RA.set(e,i)),n?i.variations??=PA(e,!0):i.plain??=PA(e,!1)}function PA(e,n){let t=new Map,i=[],r=(o,s)=>{let u=t.get(o);u?u.push(s):t.set(o,[s])};for(let o=0;o<e.length;o++){let s=e[o],u={rule:s,ordinal:o};if(s.operators!==void 0&&s.operators.length>0){for(let c of s.operators)r(c,u);continue}let a=s.match;if(a===void 0){i.push(u);continue}if(!m(a)){i.push(u);continue}let l=a.operator;if(l.startsWith("_")){i.push(u);continue}if((s.useVariations??n)&&zB.has(l)){i.push(u);continue}r(l,u)}return{byHead:t,alwaysTry:i,count:e.length}}function UB(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*Fg(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=JB.get(r);if(s!==void 0)for(let l of s){let f=e.byHead.get(l);f!==void 0&&i.push(f)}if(N(n)){let l=e.byHead.get("Divide");l!==void 0&&i.push(l)}let u=i.map(l=>UB(l,t)),a=-1;for(;;){let l=-1,f=1/0;for(let p=0;p<i.length;p++)if(u[p]<i[p].length){let d=i[p][u[p]].ordinal;d<f&&(f=d,l=p)}if(l<0)return;let c=i[l][u[l]++];c.ordinal!==a&&(a=c.ordinal,yield c)}}function DA(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 ZB={};function HB(e,n){let t=n.map(o=>o.replace),i=t.length;return{_tag:"boxed-rule",match:void 0,replace:o=>{let s=o,u;for(let a=0;a<i;a++){let l=t[a](s,ZB);if(l!=null&&"because"in l){let f=l;s=f.value,u=f}}return u},condition:void 0,operators:[e],id:`hot-head-dispatch:${e}`}}function OA(e){let n=new Map;for(let o of e){if(!DA(o))continue;let s=o.operators[0],u=n.get(s);u?u.push(o):n.set(s,[o])}let t=new Map;for(let[o,s]of n)s.length>=2&&t.set(o,HB(o,s));if(t.size===0)return e;let i=new Set,r=[];for(let o of e){if(DA(o)){let s=o.operators[0],u=t.get(s);if(u!==void 0){i.has(s)||(i.add(s),r.push(u));continue}}r.push(o)}return r}var FA=new WeakSet;var VA={boolean:e=>e.type.matches("boolean"),string:e=>B(e),number:e=>N(e),symbol:e=>I(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=>Pc(e)===!0,composite:e=>e.isInteger===!0&&e.isPositive===!0&&e.isEqual(1)===!1&&Pc(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=>dt(e.operator),equation:e=>e.operator==="Equal",inequality:e=>Xi(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 jA(e,n){for(let t of n)if(VA[t](e)!==!0)return!1;return!0}function zA(e,n){let t=e._isVerifying;e._isVerifying=!0;try{return I(n.evaluate(),"True")}finally{e._isVerifying=t}}function YB(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 WB(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(YB(r))){t=i[r];break}}if(!t)return null;for(let i of t.split(","))if(!Object.keys(VA).includes(i))throw new Error(`Unexpected condition "${i}" in a rule`);return t}function LA(e){let n=[];do{let t=WB(e);if(!t)break;n.push(t)}while(e.match(","));return n.join(",")}function Ix(e){let n=null;if(e.match(":"))n=LA(e);else if(e.matchAll(["_","<{>"])&&(n=LA(e),!e.match("<}>")))return null;return n}function QB(e){return I(e,"e")?e.engine.symbol("ExponentialE",{canonical:!1}):I(e,"i")?e.engine.I:e}function Lg(e){return e.map(QB,{canonical:!1})}function XB(e){if(m(e,"InvisibleOperator")&&I(e.ops[0],"_")){let n=e.ops.slice(1);if(n.length>0&&n.every(t=>I(t)))return e.engine.symbol("_"+n.map(t=>t.symbol).join(""))}return m(e,"Subscript")&&I(e.op1,"_")&&I(e.op2)?e.engine.symbol("__"+e.op2.symbol):e}function $A(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=Lg(r),r=r.map(XB,{canonical:!1}),t?.autoWildcard&&(r=r.map(o=>I(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 KB(e,n,t){let i=p=>({kind:"symbol",latexTrigger:p,parse:(d,g)=>{r[p]||(r[p]=`_${p}`);let h=Ix(d);return h!==null&&(o[p]?o[p]+=","+h:o[p]=h),r[p]}}),r={},o={},s=[...em,{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=Ix(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 v=!1,S=p.index;do{p.skipSpace();let _=p.nextToken();if(r[_]){let w=Ix(p);if(w===null||!w){v=!0,p.index=S;break}o[_]?o[_]+=","+w:o[_]=w}}while(!v&&!p.atEnd);b=p.parseExpression(g)}let y=[];for(let v in o){let S=o[v].split(",");S.length!==0&&(S.length===1?y.push(["Condition",r[v],S[0]]):y.push(["Condition",r[v],["And",...S]]))}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]}}],u=t?.canonical??!1,a=e._requireLatexSyntax().constructor,l=new a({dictionary:s}),f=e.contextStack[0]?.lexicalScope;f&&e.pushScope({parent:f,bindings:new Map});let c;try{if(c=e.expr(l.parse(n)??"Nothing"),!c.isValid||c.operator!=="Rule")throw new Error(`Invalid rule "${n}"
|
|
49
49
|
| ${UA(c).toString()}
|
|
50
50
|
| A rule should be of the form:
|
|
51
51
|
| <match> -> <replace>; <condition>`);if(!m(c))throw new Error(`Invalid rule "${n}"`);let[p,d,g]=c.ops,h=Lg(p),b=Lg(d),y=g!==void 0?Lg(g):void 0;if(u&&(h=h.canonical,b=b.canonical),!qA(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 tb(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?tb(e.re)+tb(e.im)+1:tb(e.re)}function Ii(e){let n=(()=>{if(!m(e,"Multiply")||e.ops.length!==2)return null;let o=(l,f)=>{if(!m(f,"Power")||!I(f.op1,"ExponentialE")||!m(l,"Power"))return null;let c=l.op2;if(!m(c,"Divide")||c.op1?.isSame(1)!==!0)return null;let p=c.op2;return!m(p,"Ln")||p.op1?.isSame(10)!==!0?null:{xBase:l.op1,eExp:f.op2}},[s,u]=e.ops,a=o(s,u)??o(u,s);return a?12+Ii(a.xBase)+Ii(a.eExp):null})();if(n!==null)return n;if(I(e))return 1;if(N(e))return tb(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+Ii(s.ops[1])}i=4}else if(t==="Sqrt"){let s=(m(e)?e:void 0)?.ops[0];if(m(s,"Multiply")){for(let u of s.ops)if(m(u,"Power")&&u.op2?.isEven===!0)return 5+Ii(s)+6}if(m(s,"Power")&&s.op2?.isEven===!0)return 5+Ii(s)+6;if(m(s,"Power")&&s.op2?.isOdd===!0&&s.op2?.isInteger===!0){let u=s.op2,a=He(u);if(typeof a=="number"&&a>1)return 5+Ii(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],u=o.ops[1],a=Ii(u);return s.operator==="Negate"?a+4:m(s,"Multiply")?s.ops.some(f=>N(f)&&f.isNegative===!0)&&u.isRational===!0&&!u.isInteger?a+Ii(s)+15:a+Ii(s):a}}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 u=s[0].numericValue,a=!1;if(typeof u=="number")a=Number.isInteger(u)&&Math.abs(u)<=10;else if(u){let l=u.type;(l==="finite_integer"&&Math.abs(u.re)<=10||l==="finite_rational")&&(a=!0)}if(a){let l=s[1].operator;return["Ln","Log","Lb"].includes(l)?2+Ii(s[1]):3+Ii(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+Ii(s),0)??0)}var vD=Ii;function WE(e,n,t){return e.generation===n&&e.value!==null||(e.generation=n,e.value=t()),e.value}var SU=[5,5],ED=0,En=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^Pi(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(cd(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"?Xo(r.result,n):we(r.result,n)},this.engine._typeResolver)}return this.engine._generation+=1,this.engine._mutationGeneration+=1,!0}bind(){this._def=xd(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=>Tn(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?ac(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=Lu(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,u]=o.toNumericValue();s.isOne||(r=r.mul(s)),u.isSame(1)||i.push(u)}return i.length===0?[r,n.One]:i.length===1?[r,i[0]]:[r,st(n,i)]}if(m(t,"Divide")){let[i,r]=t.op1.toNumericValue(),[o,s]=t.op2.toNumericValue(),u=i.div(o);return s.isSame(1)?[u,r]:[u,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 Vo(this,n,t).at(-1)?.value??null}match(n,t){return xl(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 WE(this._sgn,n,()=>{if(!(!this.isValid||this.isNumber!==!0))return Kk(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 vl(this.sgn)}get isNonNegative(){return El(this.sgn)}get isNegative(){return _l(this.sgn)}get isNonPositive(){return Sl(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 ii(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 wu(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 ze){if(n.isZero)return this.engine.Zero;if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return ge(this,this.engine.expr(n))}div(n){if(!(this.isCanonical||this.isStructural))throw new Error("Not canonical");return Ja(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 ge(...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)&&Yr(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)&&Yr(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)&&Yr(this.engine,"Ln",i)!==!0)&&(r.isNonNegative===!0||Rn(r)&&Yr(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 WE(this._type,n,()=>new Z(wU(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 _D(this.engine,()=>Jr(this,n).at(-1)?.value??this)()}explain(n,t){return yl(this,n,t)}evaluate(n){return _D(this.engine,this._computeValue(n))()}evaluateAsync(n){return TU(this.engine,this._computeValueAsync(n))()}N(){return this.evaluate({numericApproximation:!0})}solve(n){let t=Su(n??this.unknowns);if(this.operator==="List"||this.operator==="And"){let r=Zg(this.engine,this.ops,t);if(r!==null)return r}if(this.operator==="Or")return Uk(this.ops,t);if(t.length!==1)return null;if(this.operator==="Congruent"){let r=jk(this.engine,this,t[0]);if(r!==void 0)return zo(this.engine,r,t[0])}let i=rn(this,t[0]);return i===null?null:zo(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&&J(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(B(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((++ED&1023)===0&&J(this.engine._deadline),!this.isValid||!this._def)return this;let t=n?.numericApproximation??!1,i=n?.materialization??!1;if(ie(this._def))return SD(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)&&!Pe(d));if(r.broadcastable&&!s&&this.ops.some(d=>Pe(d)&&!Ye(d))&&!Pp(this.operator,o,this.ops)){let d=ou(this.engine,this.operator,this._ops,ct,t);if(d)return d;let g=ns(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 hi&&r._isLambda&&this.ops.some(d=>Pe(d)&&!Ye(d))&&Qu(r)){let d=ou(this.engine,this.operator,this._ops,ct,t);if(d)return d;let g=ns(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 CU(this,r,n);if(t&&!r.evaluate&&this.isLazyCollection){let d=T0(this.engine,this);if(d)return d}let u=qg(this,d=>d.evaluate(n)),a=r instanceof hi&&r._isLambda&&Qu(r),l=d=>N0(d)||r.lazy!==!0&&Yi(d);if((a||r.broadcastable&&this.operator!=="Add"&&this.operator!=="Multiply")&&!Pp(this.operator,!1,u)&&u.some(l)){let d=ou(this.engine,this.operator,u,ct,t);if(d)return d;let g=ns(u);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(a)return this.engine._fn("List",h);if(h.length>0)return this.engine._fn("List",h)}}if(r.broadcastable&&!NU.has(this.operator)&&u.some(d=>m(d,"When")||m(d,"Which"))){let d=IU(this.engine,this.operator,u,r.lazy===!0,n);if(d)return d}let f=this._localScope!==void 0;f&&this.engine._pushEvalContext(this._localScope);let c;try{c=r.evaluate?.(u,{numericApproximation:t,engine:this.engine,materialization:i})}finally{f&&this.engine._popEvalContext()}let p=c??(f&&r.evaluate===void 0&&this.isCanonical&&u.every((d,g)=>d===this._ops[g])?this:this.engine.function(this._operator,u));return t?Lv(this.engine,this._operator,u,p):p}}_computeValueAsync(n){return async()=>{if((++ED&1023)===0&&J(this.engine._deadline),!this.isValid||!this._def)return this;let t=n?.numericApproximation??!1;if(ie(this._def))return SD(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)&&!Pe(d));if(i?.broadcastable&&!o&&this.ops.some(d=>Pe(d)&&!Ye(d))&&!Pp(this.operator,r,this.ops)){let d=ou(this.engine,this.operator,this._ops,ct,t);if(d)return d;let g=ns(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 hi&&i._isLambda&&this.ops.some(d=>Pe(d)&&!Ye(d))&&Qu(i)){let d=ou(this.engine,this.operator,this._ops,ct,t);if(d)return d;let g=ns(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=T0(this.engine,this);if(d)return d}let s=await HA(this,async d=>await d.evaluateAsync(n)),u=i instanceof hi&&i._isLambda&&Qu(i),a=d=>N0(d)||i.lazy!==!0&&Yi(d),l=u||i.evaluate!==void 0;if((u||i.broadcastable&&this.operator!=="Add"&&this.operator!=="Multiply")&&l&&!Pp(this.operator,!1,s)&&s.some(a)){let d=ou(this.engine,this.operator,s,ct,t);if(d)return d;let g=ns(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(u)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 f=this._localScope!==void 0;f&&this.engine._pushEvalContext(this._localScope);let c=this.engine,p;try{let d={numericApproximation:t,engine:c,signal:n?.signal,materialization:n?.materialization};p=i.evaluateAsync?.(s,d)??i.evaluate?.(s,d)}finally{f&&this.engine._popEvalContext()}return Promise.resolve(p).then(d=>{let g=d??(f&&i.evaluate===void 0&&i.evaluateAsync===void 0&&this.isCanonical&&s.every((h,b)=>h===this._ops[b])?this:c.function(this._operator,s));return t?Lv(c,this._operator,s,g):g})}}};function Pp(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||gi(i)).length>=2)}var NU=new Set(["And","Or","Not","Xor","Nand","Nor","Implies","Equivalent"]);function IU(e,n,t,i,r){let o=i?t.map(s=>s.evaluate(r)):t;if(o.some(s=>m(s,"When"))){let s=[],u=o.map(f=>m(f,"When")?(s.push(f.op2),f.op1):f),a=s.length===1?s[0]:e._fn("And",s),l=e._fn(n,u).evaluate(r);return e._fn("When",[l,a]).evaluate(r)}if(o.some(s=>m(s,"Which"))){let s=o.map(f=>{if(m(f,"Which")){let c=[],p=f.ops;for(let d=0;d+1<p.length;d+=2)c.push({cond:p[d],value:p[d+1]});return c}return[{cond:null,value:f}]}),u=1;for(let f of s)u*=f.length;if(u>16)return;let a=[{conds:[],value:[]}];for(let f of s){let c=[];for(let p of a)for(let d of f)c.push({conds:d.cond?[...p.conds,d.cond]:p.conds,value:[...p.value,d.value]});a=c}let l=[];for(let f of a){let c=f.conds.length===0?e.True:f.conds.length===1?f.conds[0]:e._fn("And",f.conds);l.push(c,e._fn(n,f.value).evaluate(r))}return e._fn("Which",l).evaluate(r)}if(i)return e._fn(n,o).evaluate(r)}function wU(e){if(!e.isValid)return"error";if(e.operator==="Function"){let t=e.ops[0],i=iu(e),r=bf(e),o=`${t.type}`;r===void 0&&i.length>0&&t.type.matches("finite_number")&&!i.every(u=>u.type!==void 0&&$(u.type,"finite_number"))&&(o="number");let s=i.map(u=>u.type!==void 0?`${u.name}: ${le(u.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"&&oa.includes(o))){let o=we(...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||es(s)).length>=2)&&!Pp(e.operator,r,e.ops)){let u=(e.operator==="Add"||e.operator==="Multiply"||e.operator==="Negate")&&($(i,"collection")||typeof i!="string"&&i.kind==="union"&&i.types.some(a=>$(a,"collection")));if(e.ops.some(a=>Pe(a)&&!Ye(a)||Ed(a)||!u&&GN(a)))return fa(ca(i));if(e.ops.some(a=>gi(a)))return{kind:"broadcastable",elements:ca(i)}}}if(n instanceof hi&&n._isLambda&&Qu(n)){if(n.inferredSignature&&e.ops.some(r=>St(r)))return"any";if(e.ops.some(r=>Pe(r)&&!Ye(r)))return fa(i);if(e.ops.some(r=>gi(r)))return{kind:"broadcastable",elements:i}}return i}if(e.valueDefinition){let t=e.valueDefinition.type.type,i=bn(t)??"unknown";if(Qu(t)){if(e.valueDefinition.inferredType&&e.ops.some(r=>St(r)))return"any";if(e.ops.some(r=>Pe(r)&&!Ye(r)))return fa(i);if(e.ops.some(r=>gi(r)))return{kind:"broadcastable",elements:i}}return i}return"unknown"}function _D(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 TU(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 SD(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(u=>u.evaluate(t));if(!i||i.type.isUnknown){let u=e.engine.lookupDefinition(e.operator);return u&&fe(u)?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(u=>Pe(u)&&!Ye(u))&&Qu(s)){let u=ns(r);if(u){let a=[];for(;;){let{done:l,value:f}=u.next();if(l)break;a.push(Qt(i,f,t))}return e.engine._fn("List",a)}}return Qt(i,r,t)}function Qu(e){let n=MU(e)?e.signature?.type:e;return!n||typeof n=="string"||n.kind!=="signature"?!0:[...n.args??[],...n.optArgs??[],...n.variadicArg?[n.variadicArg]:[]].every(i=>QE(i.type))}function MU(e){return typeof e=="object"&&e!==null&&"signature"in e}function QE(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=>QE(n)):e.kind==="negation"?QE(e.type):!0}function CU(e,n,t){if(!e.isValid||t?.materialization===!1||e.isEmptyCollection===void 0)return e;let i=t?.materialization??!1;typeof i=="boolean"&&(i=SU);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 u=[];if(!e.isEmptyCollection)if(!o||!s){let l=typeof i=="number"?i:i[0],f=e.each();for(let c of f){if(u.length===l){f.next().done||u.push(e.engine.symbol("ContinuationPlaceholder"));break}u.push(c.evaluate(t))}}else{let[l,f]=typeof i=="number"?[Math.ceil(i/2),i-Math.ceil(i/2)]:i,c=1,p=e.each();for(let g of p)if(u.push(g.evaluate(t)),c+=1,c>l)break;if(u.length===0)return e;let d=e.count;if(d===void 0||d<=l)(d===void 0||u.length<d)&&u.push(e.engine.symbol("ContinuationPlaceholder"));else{let g=Math.max(l+1,d-f+1);for(d>l+f&&u.push(e.engine.symbol("ContinuationPlaceholder")),c=g;c<=d;){let h=e.at(c);if(!h)break;u.push(h.evaluate(t)),c+=1}}}if(u.length===0&&e.isEmptyCollection===!1)return e;let a=n.collection?.elttype?.(e);return a&&$(a,"tuple<string, any>")?e.engine.function("Dictionary",u):o?e.engine._fn("List",u):e.engine.function("Set",[...u])}var Vs=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 Pi("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=AU(this._string)),this._unicodeScalarValues}match(n,t){return Tr(n)||(n=this.engine.expr(n,{form:"raw"})),We(n)?{[cn(n)]:this}:n instanceof e&&this._string===n._string?{}:null}};function AU(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 Zl=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]=ID(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(B(t))r=t.string;else if(I(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(B(i))o=i.string;else if(I(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,ND(t)]))}}get hash(){return Pi("Dictionary"+JSON.stringify(this._keyValues))}get operator(){return"Dictionary"}get type(){if(this._type)return this._type;let n=we(...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])=>kU(s,t)))return this;let r=this.engine,o=i.map(([s,u])=>r._fn("KeyValuePair",[r.string(s),u.evaluate(n)]));return new e(r,r._fn("Dictionary",o))}match(n,t){if(We(n))return{[cn(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],u=n._keyValues[o];if(!s.match(u))return null;if(We(n._keyValues[o])){let a=cn(n._keyValues[o]);a&&(i={...i??{},[a]:s})}}return i}};function ND(e){return B(e)?e.string:I(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(ND):e.toMathJson({shorthands:[]})}function kU(e,n){return B(e)?!0:N(e)?!n||!e.isExact:!1}function ID(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=>ID(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 Zl(e,n.dict,t)}return e.Nothing}function RU(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 rb(e){if(!e)return{canonical:!0,structural:!1};let{form:n,canonical:t,structural:i}=e;return n!==void 0?RU(n):i===!0?{canonical:!1,structural:!0}:t!==void 0?{canonical:t,structural:!1}:{canonical:!0,structural:!1}}function XE(e,n,t){if(n instanceof je)return n;if(n=_e(n),typeof n=="string")return Zt(e,n,t);if(Array.isArray(n)){let[i,...r]=n;return new En(e,i,r.map(o=>XE(e,o,t)),{canonical:!1})}if(typeof n=="object"){if("fn"in n)return XE(e,n.fn,t);if("str"in n)return new Vs(e,n.str);if("sym"in n)return Zt(e,n.sym,t);if("num"in n)return Zt(e,n.num,t)}return Zt(e,n,t)}function ib(e,n,t,i){if(i=i?{...i}:{},"canonical"in i||(i.canonical=!0),!An(n))throw new Error(`Unexpected operator: "${n}" is not a valid symbol: ${yi(n)}`);let r=i.structural??!1;if(n==="Hold")return new En(e,"Hold",[XE(e,t[0],i)],{...i,canonical:!0,structural:r});if(n==="Error"||n==="ErrorCode")return new En(e,n,t.map(s=>e.expr(s,{form:"raw"})),{metadata:i?.metadata,canonical:!0});if(n==="Number"&&t.length===1)return Zt(e,t[0],i);if(r===!1&&i.canonical===!0){if((n==="Divide"||n==="Rational")&&t.length===2){let s=Vt(t[0]);if(s!==null){let u=Vt(t[1]);if(u!==null)return u===0n?s===0n?e.NaN:e.ComplexInfinity:e.number([s,u],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 u=ne(t[0]);return u!==null&&u!==0?e.number(e.complex(0,u),i):e.expr(s).mul(e.I)}if(t.length===2){let s=t[0]instanceof je?t[0]:Zt(e,t[0],i),u=t[1]instanceof je?t[1]:Zt(e,t[1],i);{let f=wD(s);if(f!==null){let c=wD(u);if(c!==null&&!Je(c.rational)&&(Je(f.rational)||f.radical===1&&c.radical===1)&&c.radical<=ve&&f.radical<=ve)return e.number(e._numericValue({rational:f.rational,radical:f.radical,imRational:c.rational,imRadical:c.radical}),i)}}let a=s.re,l=u.re;if(l!==null&&a!==null&&!isNaN(l)&&!isNaN(a)){if(l===0&&a===0)return e.Zero;if(l!==0){let f=s.bignumRe;return e.number(e._numericValue(f!==void 0?{re:f,im:l}:{re:a,im:l}),i)}return Zt(e,t[0],i)}return Zt(e,t[0],i).add(Zt(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 E)return e.number(s.neg(),i);let u=e.expr(s,i);if(N(u)){let a=u.numericValue;return e.number(typeof a=="number"?-a:a.neg(),i)}t=[u]}}return i.canonical===!0?FU(e,n,t,i.metadata,i.scope):Ju(new En(e,n,t.map(s=>Zt(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 KE(e){e._inferenceTxDepth+=1}function e2(e){e._inferenceTxDepth-=1,e._inferenceTxDepth===0&&(e._freshlyInferred=null)}var PU=new Set;function Zt(e,n,t){KE(e);try{return DU(e,n,t)}finally{e2(e)}}function DU(e,n,t){if(n==null)return e.error("missing");if(n instanceof ze)return $U(e,n);if(n instanceof je)return Ju(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 Zt(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 Ju(ib(e,n[0],n.slice(1),{canonical:i,structural:r,scope:t?.scope}),t?.canonical??!0,t?.scope)}if(typeof n=="number"||n instanceof E||n instanceof F)return e.number(n);if(typeof n=="boolean")return e.symbol(n?"True":"False");if(typeof n=="string"){if(Ri(n)){let o=V(n);if(!o||!An(o))return e.error("invalid-symbol",n);let s=i||t.canonical!==!1;return e.symbol(o,{canonical:s})}return xr(n)?e.number(n):(Md(n),new Vs(e,Ee(n)))}if(typeof n=="object"){let o=XN(n)?{latex:n.latex,wikidata:n.wikidata,sourceOffsets:n.sourceOffsets}:void 0;if("fn"in n){let[s,...u]=n.fn;return Ju(ib(e,s,u,{canonical:i,structural:r,metadata:o}),t.canonical,t.scope)}if("str"in n)return new Vs(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 Zl(e,n.dict,{canonical:i});throw new Error(`Unexpected MathJSON object: ${JSON.stringify(n,void 0,4)}`)}return e.symbol("Undefined")}function OU(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 FU(e,n,t,i,r){let o=LU(e,n,t,i,r);if(o)return o;if(n==="List"){let c=t.map(d=>e.expr(d,{form:"raw"})),p=wT("List",c);return p&&p.dtype?new nc(e,{ops:$i(e,c,r),shape:p.shape,dtype:p.dtype},{metadata:i}):new En(e,"List",$i(e,c,r),{canonical:!0})}if(n==="Dictionary"){let c=t.map(p=>e.expr(p,{form:"raw"}));return new Zl(e,e._fn("Dictionary",c),{canonical:!0})}let s=xd(n,r??e.context.lexicalScope);if(!s)return e.declare(n,{type:"function",inferred:!0}),new En(e,n,Ne(Xu(e,t)),{metadata:i,canonical:!0});if(ie(s)){let c=Ne(Xu(e,t)),p=s.value.type.type;if(e.strict&&!s.value.inferredType&&typeof p!="string"&&p.kind==="signature"){let d=ei(e,c,p);if(d){let g=d.map((h,b)=>{let y=c[b];return y&&y.isValid&&!h.isValid&&y.freeVariables.length>0?y:h});if(g.some(h=>!h.isValid))return new En(e,n,g,{metadata:i,canonical:!0})}}return new En(e,n,c,{metadata:i,canonical:!0})}let u=s.operator;if(r??=u.scoped?{parent:e.context.lexicalScope,bindings:new Map}:void 0,u.lazy){let c=t.map(p=>e.expr(p,{form:"raw"}));if(u.canonical){try{if(o=u.canonical(c,{engine:e,scope:r}),o)return o}catch(p){console.error(p instanceof Error?p.message:p)}return o=new En(e,n,c,{metadata:i,canonical:!1}),o}return o=new En(e,n,u.inferredSignature?c:ei(e,c,u.signature.type,u.lazy,u.broadcastable)??c,{metadata:i,canonical:!0,scope:r}),o}let a=t.map(c=>e.expr(c));if(u.canonical){try{let p=u.canonical(a,{engine:e,scope:r});if(p){if(e.strict&&!u.inferredSignature&&m(p,n)&&p.isValid&&OU(u.signature.type)){let d=wt(e,p.ops);if(d.some(g=>!g.isValid))return new En(e,n,d,{metadata:i,canonical:!0,scope:r})}return p}}catch(p){console.error(p instanceof Error?p.message:p)}return new En(e,n,a,{metadata:i,canonical:!1})}let l=Ne(a,u.associative?n:void 0),f=u.inferredSignature?null:ei(e,l,u.signature.type,u.lazy,u.broadcastable,e._inferenceTxDepth>0?e._freshlyInferred??PU:void 0);if(f){if(f.some(c=>!c.isValid))return new En(e,n,f,{metadata:i,canonical:!0,scope:r});l=f}if(l.length===1&&l[0].operator===n){if(u.involution&&m(l[0]))return l[0].op1;if(u.idempotent&&m(a[0]))return new En(e,n,a[0].ops,{metadata:i,canonical:!0,scope:r})}return new En(e,n,ac(n,l),{metadata:i,canonical:!0,scope:r})}function LU(e,n,t,i,r){let o=[];if(n==="Add"||n==="Multiply")o=wt(e,Xu(e,t,r),{flatten:n});else if(n==="Negate"||n==="Square"||n==="Sqrt"||n==="Exp")o=wt(e,Xu(e,t,r),1);else if(n==="Ln"||n==="Log")o=wt(e,Xu(e,t,r)),o.length===0&&(o=[e.error("missing")]);else if(n==="Power"||n==="Root")o=wt(e,Xu(e,t,r),2);else if(n==="Divide")o=wt(e,Xu(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 En(e,n,o,{metadata:i,canonical:!0});if(n==="Add")return Di(e,o);if(n==="Negate")return UT(o[0]);if(n==="Multiply")return st(e,o);if(n==="Divide")return o.length===2?Oi(...o):o.slice(1).reduce((s,u)=>Oi(s,u),o[0]);if(n==="Exp")return Ao(e.E,o[0]);if(n==="Square")return Ao(o[0],e.number(2));if(n==="Power")return Ao(o[0],o[1]);if(n==="Root")return Co(o[0],o[1]);if(n==="Sqrt")return Co(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 En(e,n,o,{metadata:i,canonical:!0})}return new En(e,"Log",o,{metadata:i,canonical:!0})}return null}function wD(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 Se)||t.isNaN||t.isPositiveInfinity||t.isNegativeInfinity?null:{rational:t.rational,radical:t.radical}}function $U(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 Se)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&&!Nu(n.bignumRe)?Di(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(Nt(o))t.push(s);else{let[u,a]=o;a===1?u===1?t.push(s):t.push(e.function("Multiply",[e.number(u),s])):u===1?t.push(e.function("Divide",[s,e.number(a)])):t.push(e.function("Divide",[e.function("Multiply",[e.number(u),s]),e.number(a)]))}}let r;return n.im===0?t.length===0?e.Zero:(r=t.length===1?t[0]:st(e,t),r):t.length===0?e.number(e.complex(0,n.im)):(r=t.length===1?t[0]:st(e,t),Di(e,[r,e.number(e.complex(0,n.im))]))}function Xu(e,n,t){return n.every(i=>i instanceof je&&i.isCanonical)?n:n.map(i=>e.expr(i,{scope:t}))}var AD;function kD(e){AD=e}function Hl(e,n){let t=e.latexSyntax,i=e.latexOptions;return Object.keys(i).length===0?t.serialize(n):t.serialize(n,{...i})}function TD(e,n,t,i,r){if(N(n)&&n.isNegative){let o=n.numericValue;if(typeof o=="number")return ke(e,"Subtract",[t,e.number(-o)],i,r);if(n.type.matches("rational"))return ke(e,"Subtract",[t,e.number(o.neg())],i,r)}return n.operator==="Negate"&&t.operator!=="Negate"&&m(n)?ke(e,"Subtract",[t,n.op1],i,r):null}function BU(e,n,t,i,r){let o=i.exclude;if(n==="Add"&&t.length===2&&!o.includes("Subtract")){let s=TD(e,t[0],t[1],i,r)??TD(e,t[1],t[0],i,r);if(s)return s}if(n==="Divide"&&t.length===2&&o.includes("Divide"))return ke(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?ke(e,"Negate",[t[1]],i):ke(e,"Negate",[e._fn("Multiply",[...t.slice(1)].sort(Mt))],i,r);if(n==="Multiply"&&!o.includes("Divide")){let s=new AD(e,t,{canonical:!1}).asRationalExpression();if(s.operator==="Divide"){let u=s.ops;return ke(e,s.operator,u,i,r)}}if(n==="Power"){if(!o.includes("Exp")&&I(t[0],"ExponentialE"))return ke(e,"Exp",[t[1]],i,r);if(N(t[1])){let s=Q(t[1]);if(s===2&&!o.includes("Square"))return ke(e,"Square",[t[0]],i,r);if(s!==null&&s<0&&!o.includes("Divide"))return ke(e,"Divide",[e.One,s===-1?t[0]:t[0].pow(-s)],i,r);let u=t[1].re;if(!o.includes("Sqrt")&&u===.5)return ke(e,"Sqrt",[t[0]],i,r);if(!o.includes("Sqrt")&&u===-.5)return ke(e,"Divide",[e.One,e._fn("Sqrt",[t[0]])],i,r);if(vr(u)){let a=KN(u),l=eI(u);if(a===1){if(!o.includes("Sqrt")&&l===2)return ke(e,"Sqrt",[t[0]],i,r);if(!o.includes("Root"))return ke(e,"Root",[t[0],e.number(u[1])],i,r)}if(a===-1){if(!o.includes("Sqrt")&&l===2)return ke(e,"Divide",[e.One,e._fn("Sqrt",[t[0]])],i,r);if(!o.includes("Root"))return ke(e,"Divide",[e.One,e._fn("Root",[t[0],e.number(u[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 ke(e,"Subtract",[t[0],e.number(-s)],i,r)}if(m(t[1],"Negate"))return ke(e,"Subtract",[t[0],t[1].op1],i,r)}if(n==="Tuple"){if(t.length===1&&!o.includes("Single"))return ke(e,"Single",t,i,r);if(t.length===2&&!o.includes("Pair"))return ke(e,"Pair",t,i,r);if(t.length===3&&!o.includes("Triple"))return ke(e,"Triple",t,i,r)}if(n==="Function"&&t.length>0&&m(t[0],"Block")){let s=t[0];if(s.nops===1){let u=t.slice(1);return u.every(a=>I(a)&&/_\d?/.test(a.symbol))?m(s.op1)&&s.op1.ops?.every((a,l)=>I(a)&&I(u[l])&&a.symbol===u[l].symbol)?ke(e,"Function",[e.symbol(s.op1.operator,{canonical:!1})],i,r):ke(e,"Function",[s.op1],i,r):ke(e,"Function",[s.op1,...t.slice(1)],i,r)}}return ke(e,n,t,i,r)}function ke(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 wi(e,-p,i);if(p instanceof E||p instanceof F)return wi(e,p.neg(),i);if(vr(p))return wi(e,Lt(p),i)}}if(typeof n=="string"&&o.includes(n)){if(n==="Rational"&&t.length===2)return ke(e,"Divide",t,i,r);if(n==="Complex"&&t.length===2)return ke(e,"Add",[t[0],e._fn("Multiply",[t[1]??e.symbol("Undefined"),e.I])],i,r);if(n==="Sqrt"&&t.length===1)return ke(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 ke(e,"Sqrt",[t[0]],i);if(p!==null)return p<0?ke(e,"Divide",[e.One,e._fn("Power",[t[0]??e.symbol("Undefined"),e.number([1,-p])])],i,r):ke(e,"Power",[t[0],e.number([1,-p])],i,r)}if(n==="Square"&&t.length===1)return ke(e,"Power",[t[0],e.number(2)],i,r);if(n==="Exp"&&t.length===1)return ke(e,"Power",[e.E,t[0]],i,r);if(n==="Pair"||n=="Single"||n==="Triple")return ke(e,"Tuple",t,i,r);if(n==="Subtract"&&t.length===2)return ke(e,"Add",[t[0],e._fn("Negate",[t[1]??e.symbol("Undefined")])],i,r);if(n==="Subtract"&&t.length===1)return ke(e,"Negate",t,i,r)}let s=n,u=n==="Measurement"?{...i,digits:"max",fractionalDigits:"max"}:i,a=[s,...t.map(p=>p?ob(e,p,u):"Undefined")],l={...r??{}};i.metadata.includes("latex")&&e.latexSyntax?l.latex=l.latex??Hl(e,a):l.latex="",i.metadata.includes("wikidata")||(l.wikidata=""),i.metadata.includes("sourceOffsets")||(l.sourceOffsets=void 0);let f=l.sourceOffsets;if(!l.latex&&!l.wikidata&&!f&&i.shorthands.includes("function"))return a;let c={fn:a};return l.latex&&(c.latex=l.latex),l.wikidata&&(c.wikidata=l.wikidata),f&&(c.sourceOffsets=f),c}function qU(e,n){return e=e,n.shorthands.includes("string")?xr(e)||Ri(e)?`'${e}'`:e:{str:e}}function js(e,n,t,i){if(n==="Half"&&t.exclude.includes("Half"))return wi(e,[1,2],t,i);if(i={...i},t.metadata.includes("latex")&&e.latexSyntax?(i.latex=i.latex??Hl(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")?Ri(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 MD(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 u=16,a="";for(let l=0;l<r.length-u;l++){a=r.substring(0,l);for(let f=0;f<=u;f++){let c=r.substring(l,l+f+1),p=Math.floor((r.length-a.length)/c.length);if(p<3)break;if((a+c.repeat(p+1)).startsWith(r))return c==="0"?s==="0"?i+"."+a+(o??""):e:i+"."+a+"("+c+")"+(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 CD(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 wi(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 ze){if(n.isNaN)return js(e,"NaN",t,i);if(n.isPositiveInfinity)return js(e,"PositiveInfinity",t,i);if(n.isNegativeInfinity)return js(e,"NegativeInfinity",t,i);if(n.isComplexInfinity)return js(e,"ComplexInfinity",t,i);if(r){if(n.isZero)return 0;if(n.isOne)return 1;if(n.isNegativeOne)return-1}if(n instanceof Se){if(n.im===0&&n.radical===1&&pt(n.rational))return wi(e,n.rational[0],t);let a=o.includes("Rational"),l=o.includes("Sqrt"),f={...t,digits:"max",fractionalDigits:"max"},c=g=>pt(g)?wi(e,g[0],f):[a?"Divide":"Rational",wi(e,g[0],f),wi(e,g[1],f)],p=g=>l?["Power",g,c([1,2])]:["Sqrt",g],d=(g,h)=>h===1?c(g):Nt(g)?p(h):If(g)?["Negate",p(h)]:g[0]==1?["Divide",p(h),wi(e,g[1],f)]:g[0]==-1?["Negate",["Divide",p(h),wi(e,g[1],f)]]:["Multiply",c(g),p(h)];return n.im!==0?["Complex",Je(n.rational)?0:d(n.rational,n.radical),d(n.imRational,n.imRadical)]:d(n.rational,n.radical)}if(n.im===0){let a=n.bignumRe??n.re;return wi(e,a,t,i)}return Number.isFinite(n.im)?ke(e,"Complex",[e.number(n.bignumRe??n.re),e.number(n.im)],t,{...i,wikidata:"Q11567"}):js(e,"ComplexInfinity",t,i)}let s="";if(n instanceof E){let a;if(n.isNaN())a="NaN";else if(!n.isFinite())a=n.isPositive()?"PositiveInfinity":"NegativeInfinity";else{let l=CD(t),f=typeof l=="object"&&"fractional"in l;if(r&&!(typeof l=="object")&&Nu(n))return n.toNumber();if(n.isInteger())f?s=Er(n,l.fractional):s=(n.significand<0n?-n.significand:n.significand).toString().length+n.exponent-1>20?n.toString():n.toFixed(0);else if(f)s=Er(n,l.fractional);else{let p;if(l==="max"?p=n.toString():l==="auto"?p=lu(n,e.precision).toString():p=lu(n,l.significant).toString(),s=MD(p,t),r){let d=n.toNumber();if(d.toString()===s)return d}}}return t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??Hl(e,a??{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:{num:s}}if(n instanceof F)return n.isInfinite()?js(e,"ComplexInfinity",t,i):n.isNaN()?(s="NaN",t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??Hl(e,{num:s})),i.latex!==void 0?{num:s,latex:i.latex}:{num:s}):ke(e,"Complex",[e.number(n.re),e.number(n.im)],t,{...i,wikidata:"Q11567"});if(vr(n)){let a=!o.includes("Rational");return r&&t.shorthands.includes("function")&&Yn(n)?n[0]===1&&n[1]===2&&!o.includes("Half")?js(e,"Half",t,i):[a?"Rational":"Divide",n[0],n[1]]:ke(e,a?"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??Hl(e,{num:n.toString()})),i.latex!==void 0?{num:n.toString(),latex:i.latex}:r?Tt(n,t.fractionalDigits):{num:Qn(n,t.fractionalDigits)};let u;if(Number.isNaN(n))u="NaN";else if(!Number.isFinite(n))u=n>0?"PositiveInfinity":"NegativeInfinity";else{let a=CD(t);if(typeof a=="object"&&"fractional"in a)s=Er(n,a.fractional);else{let l=n;typeof a=="object"&&"significant"in a&&!Number.isInteger(n)&&(l=lu(n,a.significant)),s=MD(l.toString(),t)}}return t.metadata.includes("latex")&&e.latexSyntax&&(i.latex=i.latex??Hl(e,{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===n.toString()?n:{num:s}}function ob(e,n,t){let i=n.wikidata;if(N(n))return wi(e,n.numericValue,t,{latex:n.verbatimLatex});if(n.rank>0)return n.json;if(Fa(n)&&Array.isArray(n.entries)){if(t.shorthands.includes("dictionary"))return n.json;let r={};for(let[o,s]of n.entries)r[o]=ob(e,s,t);return{dict:r}}if(B(n))return qU(n.string,t);if(I(n))return js(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?BU(e,n.operator,o,t,{latex:n.verbatimLatex,wikidata:i,sourceOffsets:n.sourceOffsets}):ke(e,n.operator,o,t,{latex:n.verbatimLatex,wikidata:i,sourceOffsets:n.sourceOffsets})}return n.json}function Dp(e){if(!gi(e))return!1;let n=e.type.type;return typeof n!="string"&&n.kind==="broadcastable"?!0:e.isCanonical||e.isStructural}var P=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(I(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),u=t.userFunctions,a=s===r||t.boundVars?.has(r)===!0||t.varsKeys?.has(r)===!0;if(u&&!a&&!u.misses?.has(r)){let f=e.ensureUserFunctionEmitted(n.engine,r,t);if(f!==void 0)return f;(u.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(B(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(a=>e.compile(a,o,r)).join(", ")})`;if(t==="Sum"||t==="Product"){let a=o.functions?.(t);return typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):typeof a=="string"?`${a}(${i.map(l=>e.compile(l,o)).join(", ")})`:e.compileLoop(t,i,o)}if(!e.CONTROL_FLOW_HEADS.has(t)){let a=n.lookupDefinition(t);if(fe(a)&&typeof a.operator.compile=="function"){let l=a.operator.compile(i,f=>e.compileValueOperand(f,o),{language:o.language??"javascript"});if(l!=null&&l!=="")return l}}if(o.language==="javascript"){let a=e.tryCompileBroadcast(n,t,i,o);if(a!==null)return a}if(o.language==="javascript"){let a=n.lookupDefinition(t);if((e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(a)&&a.operator.broadcastable===!0&&!dt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t))&&i.some(f=>f.isCollection||f.type.matches("list")||f.type.matches("indexed_collection")||Dp(f))){let f=o.operators?.(t),c=f===void 0||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f[0]),p=i.length===1&&fe(a)&&a.operator.broadcastable===!0&&typeof o.functions?.(t)=="function"&&Pe(i[0]);if(c&&!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 a=n.lookupDefinition(t),l=e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(a)&&a.operator.broadcastable===!0&&!dt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t),f=o.operators?.(t),c=f!==void 0&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f[0]);if(l&&c&&i.some(p=>p.isCollection||p.type.matches("list")||p.type.matches("indexed_collection")||Dp(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),f=/^[a-zA-Z_]/.test(s[0]);if(l)return`${s[0]}(${i.map(c=>e.compileValueOperand(c,o)).join(", ")})`;if(i.every(c=>!c.isCollection)){if(dt(t)&&i.length>2){let p=o.chainOp??"&&",d=[],g=i.map((y,x)=>{let v=e.compileValueOperand(y,o,s[1]),S=x>=1&&x<=i.length-2;if(o.bindExpr&&S&&!I(y)&&!N(y)){let _=e.tempVar();return d.push([_,v]),_}return v}),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 c;if(i.length===1){let p=e.compileValueOperand(i[0],o,s[1]),d=!f&&p.length>0&&p[0]===s[0][s[0].length-1],g=f||d?" ":"";c=`${s[0]}${g}${p}`}else{let p=t==="Power",d=t==="Subtract"||t==="Divide";c=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?`(${c})`:c}}if(t==="Function"){let a=o.functions?.(t);if(typeof a=="function")return a(i,f=>e.compileValueOperand(f,o),o);let l=i.slice(1).map(f=>fn(f)||"_");return`((${l.join(", ")}) => ${e.compile(i[0].canonical,{...o,var:f=>l.includes(f)?f:o.var(f),boundVars:e.withBoundNames(o,l)})})`}if(t==="Declare"){let a=I(i[0])?i[0].symbol:"_";if(o.declare)return o.declare(a);let l=e.declareValueOperand(i);return l===void 0?`let ${a}`:`let ${a} = ${e.compile(l,o)}`}if(t==="Assign")return`${I(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 a=o.functions?.(t);return typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):e.compileForLoop(i,o)}if(t==="Comprehension"){let a=o.functions?.(t);return typeof a=="function"?a(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 a=o.functions?.(t);return a?typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):`${a}(${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 a=o.functions?.(t);if(a)return typeof a=="function"?a(i,f=>e.compileValueOperand(f,o),o):`${a}(${i.map(f=>e.compile(f,o)).join(", ")})`;let l=f=>{if(f>=i.length)return"NaN";let c=i[f],p=i[f+1];return I(c,"True")?`(${e.compile(p,o)})`:`((${e.guardCondition(c,o)}) ? (${e.compile(p,o)}) : ${l(f+2)})`};return l(0)}if(t==="When"){if(i.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");let a=o.functions?.(t);if(a)return typeof a=="function"?a(i,c=>e.compileValueOperand(c,o),o):`${a}(${i.map(c=>e.compile(c,o)).join(", ")})`;if(I(i[1],"True"))return`(${e.compile(i[0],o)})`;if(I(i[1],"False"))return"NaN";let l=e.compile(i[0],o);return`((${e.guardCondition(i[1],o)}) ? (${l}) : NaN)`}if(t==="Match"){let a=o.functions?.(t);return typeof a=="function"?a(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 u=o.functions?.(t);if(!u){let a=e.tryCompileUserFunction(n,t,i,o);if(a!==void 0)return a;throw new Error(`Unknown operator \`${t}\``)}if(typeof u=="function"){let a=n.lookupDefinition(t);if(fe(a)&&a.operator.broadcastable&&i.length===1&&Pe(i[0])){let l=e.tempVar(),f={...o,var:c=>c===l?l:o.var(c),boundVars:e.withBoundNames(o,[l])};return`(${e.compile(i[0],o)}).map((${l}) => ${u([i[0].engine.expr(l)],c=>e.compileValueOperand(c,f),f)})`}return u(i,l=>e.compileValueOperand(l,o),o)}if(o.language!==void 0&&!o.language.startsWith("interval")&&!e.COMPLEX_TRANSPARENT_HEADS.has(t)&&i.some(a=>e.isComplexValued(a)))throw new Error(`${t}: real-only target helper "${u}" cannot represent a complex-valued argument. Fail closed (D6).`);return`${u}(${i.map(a=>e.compileValueOperand(a,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||dt(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 u=g=>{let h=De(g.type.type);return h===void 0?!1:pi(h)};if(t==="Multiply"){let g=b=>mi(b)||St(b)||b.type.matches("list")||b.type.matches("indexed_collection")||Dp(b),h=i.filter(g);if(h.length>=2){if(h.some(Dp))return i.some(v=>e.isComplexValued(v)||u(v))?null:`_SYS.mul(${i.map(v=>e.compile(v,r)).join(", ")})`;let b=x=>mi(x)&&x.shape.length>=2||x.type.matches("matrix");if(h.some(x=>St(x))||i.some(b))return null;let y=h.filter(x=>mi(x)&&x.shape.length===1).map(x=>x.shape[0]);if(y.length>=2&&new Set(y).size>1)return null}}let a=r.functions?.(t);if(typeof a!="function")return null;let l=g=>g.isCollection||g.type.matches("list")||g.type.matches("indexed_collection")||Dp(g);if(!i.some(l)||i.some(g=>e.isComplexValued(g)||u(g)))return null;let f=i.map(()=>e.tempVar()),c={...r,var:g=>f.includes(g)?g:r.var(g),boundVars:e.withBoundNames(r,f)},p=a(f.map(g=>n.expr(g)),g=>e.compileValueOperand(g,c),c),d=i.map(g=>e.compile(g,r)).join(", ");return`_SYS.bcast((${f.join(", ")}) => ${p}, ${d})`}static declareValueOperand(n){let t=n.slice(1),i,r=t[t.length-1];return r!==void 0&&Yt(r)&&(i=r.get("value"),t=t.slice(0,-1)),t[1]??i}static compileBlock(n,t){let i=[];for(let u of n)if(m(u,"Declare")){let a=u.ops[0];I(a)&&i.push(a.symbol)}if(n.length===1&&i.length===0)return e.compile(n[0],t);let r={};if(t.declare&&t.language){let a=t.language==="wgsl"?"vec2f":"vec2";for(let l of i)for(let f of n){if(m(f,"Declare")&&I(f.ops[0],l)&&I(f.ops[1],"complex")){r[l]=a;break}if(m(f,"Assign")&&I(f.ops[0],l)){e.isComplexValued(f.ops[1])&&(r[l]=a);break}}}let o={...t,var:u=>i.includes(u)?u:t.var(u),boundVars:e.withBoundNames(t,i)},s=n.filter(u=>!I(u,"Nothing")).flatMap(u=>{if(m(u,"Declare")&&I(u.ops[0])&&t.declare){let a=u.ops[0].symbol,l=t.declare(a,r[a]),f=e.declareValueOperand(u.ops);return f!==void 0?[l,`${a} = ${e.compile(f,o)}`]:[l]}return[e.compile(u,o)]}).filter(u=>u!=="");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(I(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),u=t.userFunctions,a=s===r||t.boundVars?.has(r)===!0||t.varsKeys?.has(r)===!0;if(u&&!a&&!u.misses?.has(r)){let f=e.ensureUserFunctionEmitted(n.engine,r,t);if(f!==void 0)return f;(u.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(B(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(a=>e.compile(a,o,r)).join(", ")})`;if(t==="Sum"||t==="Product"){let a=o.functions?.(t);return typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):typeof a=="string"?`${a}(${i.map(l=>e.compile(l,o)).join(", ")})`:e.compileLoop(t,i,o)}if(!e.CONTROL_FLOW_HEADS.has(t)){let a=n.lookupDefinition(t);if(fe(a)&&typeof a.operator.compile=="function"){let l=a.operator.compile(i,f=>e.compileValueOperand(f,o),{language:o.language??"javascript"});if(l!=null&&l!=="")return l}}if(o.language==="javascript"){let a=e.tryCompileBroadcast(n,t,i,o);if(a!==null)return a}if(o.language==="javascript"){let a=n.lookupDefinition(t);if((e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(a)&&a.operator.broadcastable===!0&&!dt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t))&&i.some(f=>f.isCollection||f.type.matches("list")||f.type.matches("indexed_collection")||Dp(f))){let f=o.operators?.(t),c=f===void 0||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f[0]),p=i.length===1&&fe(a)&&a.operator.broadcastable===!0&&typeof o.functions?.(t)=="function"&&Pe(i[0]);if(c&&!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 a=n.lookupDefinition(t),l=e.SCALAR_ARITHMETIC_HEADS.has(t)||fe(a)&&a.operator.broadcastable===!0&&!dt(t)&&!e.LOGICAL_BROADCAST_HEADS.has(t),f=o.operators?.(t),c=f!==void 0&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f[0]);if(l&&c&&i.some(p=>p.isCollection||p.type.matches("list")||p.type.matches("indexed_collection")||Dp(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),f=/^[a-zA-Z_]/.test(s[0]);if(l)return`${s[0]}(${i.map(c=>e.compileValueOperand(c,o)).join(", ")})`;if(i.every(c=>!c.isCollection)){if(dt(t)&&i.length>2){let p=o.chainOp??"&&",d=[],g=i.map((y,x)=>{let v=e.compileValueOperand(y,o,s[1]),S=x>=1&&x<=i.length-2;if(o.bindExpr&&S&&!I(y)&&!N(y)){let _=e.tempVar();return d.push([_,v]),_}return v}),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 c;if(i.length===1){let p=e.compileValueOperand(i[0],o,s[1]),d=!f&&p.length>0&&p[0]===s[0][s[0].length-1],g=f||d?" ":"";c=`${s[0]}${g}${p}`}else{let p=t==="Power",d=t==="Subtract"||t==="Divide";c=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?`(${c})`:c}}if(t==="Function"){let a=o.functions?.(t);if(typeof a=="function")return a(i,f=>e.compileValueOperand(f,o),o);let l=i.slice(1).map(f=>fn(f)||"_");return`((${l.join(", ")}) => ${e.compile(i[0].canonical,{...o,var:f=>l.includes(f)?f:o.var(f),boundVars:e.withBoundNames(o,l)})})`}if(t==="Declare"){let a=I(i[0])?i[0].symbol:"_";if(o.declare)return o.declare(a);let l=e.declareValueOperand(i);return l===void 0?`let ${a}`:`let ${a} = ${e.compile(l,o)}`}if(t==="Assign")return`${I(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 a=o.functions?.(t);return typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):e.compileForLoop(i,o)}if(t==="Comprehension"){let a=o.functions?.(t);return typeof a=="function"?a(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 a=o.functions?.(t);return a?typeof a=="function"?a(i,l=>e.compileValueOperand(l,o),o):`${a}(${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 a=o.functions?.(t);if(a)return typeof a=="function"?a(i,f=>e.compileValueOperand(f,o),o):`${a}(${i.map(f=>e.compile(f,o)).join(", ")})`;let l=f=>{if(f>=i.length)return"NaN";let c=i[f],p=i[f+1];return I(c,"True")?`(${e.compile(p,o)})`:`((${e.guardCondition(c,o)}) ? (${e.compile(p,o)}) : ${l(f+2)})`};return l(0)}if(t==="When"){if(i.length!==2)throw new Error("When: expected exactly 2 arguments (expr, cond)");let a=o.functions?.(t);if(a)return typeof a=="function"?a(i,c=>e.compileValueOperand(c,o),o):`${a}(${i.map(c=>e.compile(c,o)).join(", ")})`;if(I(i[1],"True"))return`(${e.compile(i[0],o)})`;if(I(i[1],"False"))return"NaN";let l=e.compile(i[0],o);return`((${e.guardCondition(i[1],o)}) ? (${l}) : NaN)`}if(t==="Match"){let a=o.functions?.(t);return typeof a=="function"?a(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 u=o.functions?.(t);if(!u){let a=e.tryCompileUserFunction(n,t,i,o);if(a!==void 0)return a;throw new Error(`Unknown operator \`${t}\``)}if(typeof u=="function"){let a=n.lookupDefinition(t);if(fe(a)&&a.operator.broadcastable&&i.length===1&&Pe(i[0])){let l=e.tempVar(),f={...o,var:c=>c===l?l:o.var(c),boundVars:e.withBoundNames(o,[l])};return`(${e.compile(i[0],o)}).map((${l}) => ${u([i[0].engine.expr(l)],c=>e.compileValueOperand(c,f),f)})`}return u(i,l=>e.compileValueOperand(l,o),o)}if(o.language!==void 0&&!o.language.startsWith("interval")&&!e.COMPLEX_TRANSPARENT_HEADS.has(t)&&i.some(a=>e.isComplexValued(a)))throw new Error(`${t}: real-only target helper "${u}" cannot represent a complex-valued argument. Fail closed (D6).`);return`${u}(${i.map(a=>e.compileValueOperand(a,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||dt(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 u=g=>{let h=De(g.type.type);return h===void 0?!1:pi(h)};if(t==="Multiply"){let g=b=>mi(b)||St(b)||b.type.matches("list")||b.type.matches("indexed_collection")||Dp(b),h=i.filter(g);if(h.length>=2){if(h.some(Dp))return i.some(v=>e.isComplexValued(v)||u(v))?null:`_SYS.mul(${i.map(v=>e.compile(v,r)).join(", ")})`;let b=x=>mi(x)&&x.shape.length>=2||x.type.matches("matrix");if(h.some(x=>St(x))||i.some(b))return null;let y=h.filter(x=>mi(x)&&x.shape.length===1).map(x=>x.shape[0]);if(y.length>=2&&new Set(y).size>1)return null}}let a=r.functions?.(t);if(typeof a!="function")return null;let l=g=>g.isCollection||g.type.matches("list")||g.type.matches("indexed_collection")||Dp(g);if(!i.some(l)||i.some(g=>e.isComplexValued(g)||u(g)))return null;let f=i.map(()=>e.tempVar()),c={...r,var:g=>f.includes(g)?g:r.var(g),boundVars:e.withBoundNames(r,f)},p=a(f.map(g=>n.expr(g)),g=>e.compileValueOperand(g,c),c),d=i.map(g=>e.compile(g,r)).join(", ");return`_SYS.bcast((${f.join(", ")}) => ${p}, ${d})`}static declareValueOperand(n){let t=n.slice(1),i,r=t[t.length-1];return r!==void 0&&Yt(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];I(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 a of n)if(m(a,"Declare")&&I(a.ops[0])){let l=a.ops[0].symbol;I(a.ops[1],"complex")&&r.set(l,!0);let f=e.declareValueOperand(a.ops);f!==void 0&&e.isComplexValued(f)&&r.set(l,!0)}else m(a,"Assign")&&I(a.ops[0])&&r.get(a.ops[0].symbol)===!1&&e.isComplexValued(a.ops[1])&&r.set(a.ops[0].symbol,!0);let o={};if(t.declare&&t.language){let a=t.language==="wgsl"?"vec2f":"vec2";for(let l of i)r.get(l)&&(o[l]=a)}let s={...t,var:a=>i.includes(a)?a:t.var(a),boundVars:e.withBoundNames(t,i)},u=n.filter(a=>!I(a,"Nothing")).flatMap(a=>{if(m(a,"Declare")&&I(a.ops[0])&&t.declare){let l=a.ops[0].symbol,f=t.declare(l,o[l]),c=e.declareValueOperand(a.ops);return c!==void 0?[f,`${l} = ${e.compile(c,s)}`]:[f]}return[e.compile(a,s)]}).filter(a=>a!=="");return u.length===0?"":t.block?t.block(u):(u[u.length-1]=`return ${u[u.length-1]}`,`(() => {${t.ws(`
|
|
90
|
+
`)}${u.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 u=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 u=e.compileLoopBody(i,t);return`(() => {${t.ws(`
|
|
93
93
|
`)}while (true) {${t.ws(`
|
|
94
94
|
`)}${u}${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(I(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(I(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(pi(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 pi(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(I(n,"True")||I(n,"False"))return!0;if(m(n)){let t=n.operator;if(dt(t)||t==="And"||t==="Or"||t==="Not")return!0;let i=n.type;return i?i.matches("boolean"):!1}if(I(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(B(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)||B(o)||I(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 u=e.matchCaseComparisons(t).map(a=>`${i} ${r} ${e.compileMatchConstant(n,a,o,s)}`);return u.length===0?"false":u.length===1?u[0]:`(${u.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=Mh(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
|
`),u=[],a=!1;for(let f of r.segments){if(a)break;if(f.kind==="dispatch"&&e.matchSwitchable(f)){u.push(e.emitMatchSwitch(n,f,o,i));continue}for(let c of f.cases){if(a)break;if(e.isIrrefutableCase(c)){let p=c.captureNames.length===1?new Map([[c.captureNames[0],o]]):void 0;u.push(`return ${e.compileMatchBody(c,p,i)};`),a=!0;break}u.push(e.emitMatchCaseJS(n,c,o,i))}}a||u.push("return NaN;");let l=e.compile(t[0],i);return`((${o}) => {${s}${u.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),u=e.compileMatchGuard(t,void 0,r);return`if (${u===void 0?s:`(${s}) && (${u})`}) return ${e.compileMatchBody(t,void 0,r)};`}if(t.tier===2){let s=[],u=new Map;e.walkMatchShape(n,t.shape,i,s,u,r);let a=e.compileMatchGuard(t,u,r);a!==void 0&&s.push(`(${a})`);let l=e.compileMatchBody(t,u,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(f=>`'${f.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 u=t.prefix.length+t.suffix.length;t.rest===void 0?r.push(`${i}.length === ${u}`):r.push(`${i}.length >= ${u}`),t.prefix.forEach((l,f)=>e.walkMatchElement(n,l,`${i}[${f}]`,r,o,s));let a=t.suffix.length;if(t.suffix.forEach((l,f)=>e.walkMatchElement(n,l,`${i}[${i}.length - ${a} + ${f}]`,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 - ${a})`)}}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,u=[];for(let a of t.cases){let l=[];for(let f of a.dispatchKeys??[]){let c=Number(f.key.slice(2));s.has(c)||(s.add(c),l.push(`case ${c}:`))}l.length!==0&&u.push(`${l.join(" ")} return ${e.compileMatchBody(a,void 0,r)};`)}return`switch (${i}) {${o}${u.join(o)}${o}}`}static compileMatchTernary(n,t,i,r){let o=Mh(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),u=o.segments.flatMap(l=>l.cases),a=l=>{if(l>=u.length)return r.noMatch;let f=u[l];if(e.isIrrefutableCase(f)){let p=f.captureNames.length===1?new Map([[f.captureNames[0],s]]):void 0;return e.compileMatchBody(f,p,i)}if(f.tier===0||f.tier===1){let p=e.matchLeafCondition(n,f,s,r.eq,r.allowStrings,i),d=e.compileMatchGuard(f,void 0,i),g=d===void 0?p:`(${p}) && (${d})`;return r.ternary(g,e.compileMatchBody(f,void 0,i),a(l+1))}if(f.tier===2)throw new Error(`Match: list/tuple destructuring is not compilable to "${i.language??"this"}". Fail closed (D6).`);let c=f.rawPatterns?.[0];throw new Error(`Match: pattern '${c?.toString()??"?"}' is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)};return a(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(u=>e.compileValueOperand(u,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 u=o.ops.slice(1).map(l=>fn(l)||"_"),a=e.compile(o.ops[0].canonical,{...i,var:l=>u.includes(l)?l:i.var(l)});r.defs.set(s,`const ${s} = (${u.join(", ")}) => ${a};`)}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,u=[];for(let a of t.cases){let l=[];for(let f of a.dispatchKeys??[]){let c=Number(f.key.slice(2));s.has(c)||(s.add(c),l.push(`case ${c}:`))}l.length!==0&&u.push(`${l.join(" ")} return ${e.compileMatchBody(a,void 0,r)};`)}return`switch (${i}) {${o}${u.join(o)}${o}}`}static compileMatchTernary(n,t,i,r){let o=Mh(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),u=o.segments.flatMap(l=>l.cases),a=l=>{if(l>=u.length)return r.noMatch;let f=u[l];if(e.isIrrefutableCase(f)){let p=f.captureNames.length===1?new Map([[f.captureNames[0],s]]):void 0;return e.compileMatchBody(f,p,i)}if(f.tier===0||f.tier===1){let p=e.matchLeafCondition(n,f,s,r.eq,r.allowStrings,i),d=e.compileMatchGuard(f,void 0,i),g=d===void 0?p:`(${p}) && (${d})`;return r.ternary(g,e.compileMatchBody(f,void 0,i),a(l+1))}if(f.tier===2)throw new Error(`Match: list/tuple destructuring is not compilable to "${i.language??"this"}". Fail closed (D6).`);let c=f.rawPatterns?.[0];throw new Error(`Match: pattern '${c?.toString()??"?"}' is not compilable; rewrite with destructuring or guards. Fail closed (D6).`)};return a(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(u=>e.compileValueOperand(u,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 u=o.ops.slice(1).map(l=>fn(l)||"_"),a=e.compile(o.ops[0].canonical,{...i,var:l=>u.includes(l)?l:i.var(l),boundVars:e.withBoundNames(i,u)});r.defs.set(s,`const ${s} = (${u.join(", ")}) => ${a};`)}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,u=new Set,a=new Set,l=(c,p)=>{let d=new Set(c);for(let g of p)d.add(g);return d},f=(c,p)=>{if(I(c)){let y=c.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 v=e.userFunctionLiteral(r,y);if(v!==void 0){if(!a.has(y)){a.add(y);let S=v.ops.slice(1).map(_=>fn(_)).filter(_=>_!=="");f(v.ops[0],S.length?l(p,S):p)}return}}let x=r._getSymbolValue(y);if(x!==void 0){u.has(y)||(u.add(y),f(x,p));return}o.add(y);return}if(!m(c))return;let d=c.operator,g=c.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,v=>e.compileValueOperand(v,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(!a.has(d)){a.add(d);let y=h.ops.slice(1).map(x=>fn(x)).filter(x=>x!=="");f(h.ops[0],y.length?l(p,y):p)}for(let y of g)f(y,p);return}if(d==="Function"){let y=g.slice(1).map(x=>fn(x)).filter(x=>x!=="");f(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 v of g.slice(1))if(m(v)){I(v.ops[0])&&y.push(v.ops[0].symbol);for(let S of v.ops.slice(1))x.push(S)}else x.push(v);f(g[0],y.length?l(p,y):p);for(let v of x)f(v,p);return}if(d==="Block"){let y=[];for(let v of g)m(v,"Declare")&&I(v.ops[0])&&y.push(v.ops[0].symbol);let x=y.length?l(p,y):p;for(let v of g)f(v,x);return}if(d==="Match"){g[0]!==void 0&&f(g[0],p);for(let y of g.slice(1)){if(!m(y,"MatchCase")||y.ops.length<2)continue;let x=y.ops,v=x[0],S=x.length>=3?x[1]:void 0,_=x[x.length-1],{captures:w,pinExprs:M}=N5(v),A=w.length?l(p,w):p;S!==void 0&&f(S,A),f(_,A);for(let k of M)f(k,p)}return}for(let y of g)f(y,p)};return f(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,u=f=>f.isCollection?[...f.each()].map(u):f.re,a={freeSymbols:[],unsupported:[]};try{r&&(a=e.analyzeReferences(n,r,o))}catch{}return m(n,"Function")?{target:i,success:!1,code:"",calling:"lambda",run:((...c)=>s.function("Apply",[n,...c.map(p=>s.expr(p))]).evaluate().re),error:t,...a}:{target:i,success:!1,code:"",calling:"expression",run:(f=>{s.pushScope();try{if(f&&typeof f=="object")for(let[c,p]of Object.entries(f))s.declare(c,"number"),s.assign(c,p);return u(n.evaluate())}finally{s.popScope()}}),error:t,...a}}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 VU=new Set(["Sin","Cos","Tan","Cot","Sec","Csc","Haversine"]),jU=new Set(["Arcsin","Arccos","Arctan","Arctan2","Arccot","Arcsec","Arccsc","InverseHaversine"]);function ro(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,u=o.ops.map(l=>{let f=r(l);return f!==l&&(s=!0),f}),a=o.operator;if(VU.has(a)&&u.length===1)return n.function(a,[n.function("Multiply",[n.number(i),u[0]])]);if(jU.has(a)&&u.length>=1){let l=s?n.function(a,u):o;return n.function("Multiply",[n.number(1/i),l])}return s?n.function(a,u):o};return r(e)}function zs(e){return typeof e=="object"&&e!==null}function RD(e){return typeof e=="number"&&Number.isFinite(e)}function PD(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 DD(e){return PD(e,{kind:"compilation target"})}function OD(e){return PD(e,{kind:"library"})}var zU=["getOperators","getFunctions","createTarget","compile"];function FD(e){if(!zs(e))throw new Error("Invalid compilation target: expected an object implementing LanguageTarget");for(let n of zU)if(typeof e[n]!="function")throw new Error(`Invalid compilation target: missing required method "${n}()"`)}function JU(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=OD(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 GU(e,n){if(e===void 0)return;let t=Array.isArray(e)?e:[e];for(let i of t)if(!zs(i)||Array.isArray(i))throw new Error(`Invalid library "${n}": "definitions" must be an object or an array of objects`)}function LD(e){if(!zs(e)||Array.isArray(e))throw new Error('Invalid library definition: expected an object with at least a "name" field');let n=OD(e.name);JU(e.requires,n),GU(e.definitions,n)}function UU(e){if(!zs(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(!RD(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 ZU(e,n){if(n!==void 0&&(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!RD(n[1])))throw new Error(`Invalid compilation option "operators.${e}": expected [string, number]`)}function HU(e){if(e!==void 0&&typeof e!="function"){if(!zs(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))ZU(n,t)}}function YU(e){if(e!==void 0){if(!zs(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 WU(e){if(e!==void 0){if(!zs(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 QU(e){if(e!==void 0&&!Array.isArray(e))throw new Error('Invalid compilation option "imports": expected an array')}function $D(e){if(e!==void 0){if(!zs(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&&UU(e.target),HU(e.operators),YU(e.functions),WU(e.vars),QU(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 Op(e,n){$D(n);try{if(n?.target){let r=P.compile(ro(e),n.target);return P.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 P.buildInterpreterFallback(e,i,r,o,n?.vars?new Set(Object.keys(n.vars)):void 0)}throw t}}ON(Ae);dI(Ae);pI(ob);kD(ii);RN(Op);gI(de);hI(ue);yI(rn);qN(ei);function BD(e){let n={And:Xm,Or:Km,Not:eg,Equivalent:ng,Implies:tg,Xor:ig,Nand:rg,Nor:og}[e.operator];if(!n||!m(e))return;let t=n(e.ops,{engine:e.engine});if(t)return{value:t,because:"logic"}}function qD(e){if(!m(e,"Sum"))return;let n=e.op1,t=e.op2;if(!n||!m(t,"Limits"))return;let i=T(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 a=n.simplify();if(!a.isSame(n))return{value:s.function("Sum",[a,t]),because:"simplified nested sum/product"}}if(N(r)&&N(o)){let a=r.numericValue,l=o.numericValue;if(typeof a=="number"&&typeof l=="number"&&Number.isInteger(a)&&Number.isInteger(l)){if(l<a)return{value:s.Zero,because:"empty sum"};if(l===a)return{value:n.subs({[i]:r}).simplify(),because:"single term sum"}}}if(!new Set(n.unknowns).has(i)){let a=o.sub(r).add(s.One).simplify();return N(a)&&a.numericValue!==void 0&&(typeof a.numericValue=="number"?a.numericValue:a.numericValue.re)<=0?{value:s.Zero,because:"empty sum"}:{value:a.mul(n.simplify()),because:"sum of constant"}}if(T(n)===i){let a=r,l=o;return{value:l.mul(l.add(s.One)).sub(a.mul(a.sub(s.One))).div(2).simplify(),because:"triangular number"}}if(m(n,"Power")&&T(n.op1)===i&&n.op2.isSame(2)&&r.isSame(1)){let a=o;return{value:a.mul(a.add(s.One)).mul(a.mul(2).add(s.One)).div(6),because:"sum of squares"}}if(m(n,"Power")&&T(n.op1)===i&&n.op2.isSame(3)&&r.isSame(1)){let a=o;return{value:a.mul(a.add(s.One)).div(2).pow(2),because:"sum of cubes"}}if(m(n,"Power")&&n.op1.isSame(-1)&&T(n.op2)===i&&r.isSame(0)){let a=o;return{value:s.One.add(s.number(-1).pow(a)).div(2),because:"alternating unit series"}}if(m(n,"Multiply")&&r.isSame(0)){let a=!1,l=!1;for(let f of n.ops)m(f,"Power")&&f.op1.isSame(-1)&&T(f.op2)===i?a=!0:T(f)===i&&(l=!0);if(a&&l&&n.ops.length===2){let f=o;return{value:s.function("Multiply",[s.function("Power",[s.number(-1),f]),s.function("Floor",[s.function("Divide",[s.function("Add",[f,s.One]),s.number(2)])])]),because:"alternating linear series"}}}if(m(n,"Add")){let a=null,l=null;for(let f of n.ops)if(!new Set(f.unknowns).has(i))a=a?a.add(f):f;else if(T(f)===i)l=l?l.add(s.One):s.One;else if(m(f,"Multiply")&&f.ops.some(p=>T(p)===i)){let p=f.ops.filter(d=>T(d)!==i);if(p.length===f.ops.length-1){let d=p.length===1?p[0]:s.function("Multiply",p);l=l?l.add(d):d}}else{a=null,l=null;break}if(a!==null&&l!==null){let f=r,c=o;if(r.isSame(0)){let p=s.function("Add",[c,s.One]),d=s.function("Add",[a,s.function("Divide",[s.function("Multiply",[l,c]),s.number(2)])]);return{value:s.function("Multiply",[p,d]),because:"arithmetic progression"}}else{let p=s.function("Add",[s.function("Subtract",[c,f]),s.One]),d=s.function("Divide",[s.function("Add",[f,c]),s.number(2)]),g=s.function("Add",[a,s.function("Multiply",[l,d])]);return{value:s.function("Multiply",[p,g]),because:"arithmetic progression"}}}}if(m(n,"Power")&&T(n.op2)===i&&!new Set(n.op1.unknowns).has(i)){let a=n.op1,l=o;if(r.isSame(0)){let f=s.One.sub(a.pow(l.add(s.One))),c=s.One.sub(a);return{value:f.div(c),because:"geometric series"}}else if(r.isSame(1)){let f=a.sub(a.pow(l.add(s.One))),c=s.One.sub(a);return{value:f.div(c),because:"geometric series"}}}if(m(n,"Binomial")&&r.isSame(0)&&T(n.op2)===i){let a=n.op1;if(a&&o.isSame(a))return{value:s.function("Power",[s.number(2),a]),because:"sum of binomial coefficients"}}if(m(n,"Multiply")&&r.isSame(0)){let a=!1,l=!1,f=null;for(let b of n.ops)m(b,"Binomial")&&T(b.op2)===i?(a=!0,f=b.op1??null):m(b,"Power")&&b.op1.isSame(-1)&&T(b.op2)===i&&(l=!0);if(a&&l&&f&&o.isSame(f)&&f.isGreater(0)===!0)return{value:s.Zero,because:"alternating binomial sum"};let c=!1;f=null,a=!1;for(let b of n.ops)T(b)===i?c=!0:m(b,"Binomial")&&T(b.op2)===i&&(a=!0,f=b.op1??null);if(c&&a&&f&&o.isSame(f)&&n.ops.length===2){let b=f;return{value:s.function("Multiply",[b,s.function("Power",[s.number(2),b.sub(s.One)])]),because:"weighted binomial sum"}}let p=!1;f=null,a=!1;for(let b of n.ops)m(b,"Power")&&T(b.op1)===i&&b.op2.isSame(2)?p=!0:m(b,"Binomial")&&T(b.op2)===i&&(a=!0,f=b.op1??null);if(p&&a&&f&&o.isSame(f)&&n.ops.length===2){let b=f;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;f=null,a=!1;for(let b of n.ops)m(b,"Power")&&T(b.op1)===i&&b.op2.isSame(3)?d=!0:m(b,"Binomial")&&T(b.op2)===i&&(a=!0,f=b.op1??null);if(d&&a&&f&&o.isSame(f)&&n.ops.length===2){let b=f;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;f=null,a=!1;for(let b of n.ops)m(b,"Power")&&b.op1.isSame(-1)&&T(b.op2)===i?g=!0:T(b)===i?h=!0:m(b,"Binomial")&&T(b.op2)===i&&(a=!0,f=b.op1??null);if(g&&h&&a&&f&&o.isSame(f)&&n.ops.length===3&&f.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 a=n.op1,l=a.op1,f=a.op2;if(l&&T(f)===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[a,l]=n.ops;if(T(a)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(c=>T(c)===i)&&l.ops.some(c=>c.isSame(1))||T(l)===i&&a.operator==="Add"&&m(a)&&a.ops.length===2&&a.ops.some(c=>T(c)===i)&&a.ops.some(c=>c.isSame(1))){let c=o;return{value:s.function("Divide",[s.function("Multiply",[c,s.function("Add",[c,s.One]),s.function("Add",[c,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 a=n.op2;if(a.ops.length===2){let[l,f]=a.ops;if(r.isSame(1)&&(T(l)===i&&f.operator==="Add"&&m(f)&&f.ops.length===2&&f.ops.some(p=>T(p)===i)&&f.ops.some(p=>p.isSame(1))||T(f)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(p=>T(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)&&(T(l)===i&&f.operator==="Add"&&m(f)&&f.ops.length===2&&f.ops.some(p=>T(p)===i)&&f.ops.some(p=>p.isSame(-1))||T(f)===i&&l.operator==="Add"&&m(l)&&l.ops.length===2&&l.ops.some(p=>T(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 a=[],l=[];for(let f of n.ops)new Set(f.unknowns).has(i)?l.push(f):a.push(f);if(a.length>0&&l.length>0){let f=a.length===1?a[0]:s.function("Multiply",a),c=l.length===1?l[0]:s.function("Multiply",l),p=s.function("Sum",[c,t]);return{value:f.mul(p),because:"factor out constant from sum"}}}}function VD(e){if(!m(e,"Product"))return;let n=e.op1,t=e.op2;if(!n||!m(t,"Limits"))return;let i=T(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 a=n.simplify();if(!a.isSame(n))return{value:s.function("Product",[a,t]),because:"simplified nested sum/product"}}if(N(r)&&N(o)){let a=r.numericValue,l=o.numericValue;if(typeof a=="number"&&typeof l=="number"&&Number.isInteger(a)&&Number.isInteger(l)){if(l<a)return{value:s.One,because:"empty product"};if(l===a)return{value:n.subs({[i]:r}).simplify(),because:"single term product"}}}if(!new Set(n.unknowns).has(i)){let a=o.sub(r).add(s.One).simplify();return N(a)&&a.numericValue!==void 0&&(typeof a.numericValue=="number"?a.numericValue:a.numericValue.re)<=0?{value:s.One,because:"empty product"}:{value:n.simplify().pow(a),because:"product of constant"}}if(T(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[a,l]=n.ops,f=null,c=null;if(T(a)===i&&!new Set(l.unknowns).has(i)?(f=a,c=l):T(l)===i&&!new Set(a.unknowns).has(i)&&(f=l,c=a),f&&c){let p=o,d=c;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 a=n.op1,l=n.op2;if(T(l)===i&&a.operator==="Add"&&m(a)&&a.ops.length===2&&a.ops.some(f=>T(f)===i)&&a.ops.some(f=>f.isSame(1)))return{value:o.add(s.One),because:"telescoping product"}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(2)){let a=!1,l=!1;for(let f of n.ops)f.isSame(1)?a=!0:m(f,"Negate")&&f.op1.operator==="Power"&&m(f.op1)&&T(f.op1.op1)===i&&f.op1.op2.isSame(-2)?l=!0:m(f,"Power")&&T(f.op1)===i&&f.op2.isSame(-2)||m(f,"Multiply")&&f.ops.some(c=>c.isSame(-1))&&f.ops.some(c=>m(c,"Power")&&T(c.op1)===i&&c.op2.isSame(-2))&&(l=!0);if(a&&l){let f=o;return{value:s.function("Divide",[s.function("Add",[f,s.One]),s.function("Multiply",[s.number(2),f])]),because:"Wallis-like product"}}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(1)){let a=!1,l=0,f=0;for(let c of n.ops)if(N(c)&&typeof c.numericValue=="number")f=c.numericValue;else if(m(c,"Multiply")&&c.ops.length===2){let[p,d]=c.ops;N(p)&&typeof p.numericValue=="number"&&T(d)===i?(l=p.numericValue,a=!0):N(d)&&typeof d.numericValue=="number"&&T(p)===i&&(l=d.numericValue,a=!0)}if(a&&l===2&&f===-1){let c=o;return{value:s.function("Factorial2",[s.function("Subtract",[s.function("Multiply",[s.number(2),c]),s.One])]),because:"odd double factorial"}}}if(m(n,"Multiply")&&n.ops.length===2&&r.isSame(1)){let[a,l]=n.ops;if(a.isSame(2)&&T(l)===i||l.isSame(2)&&T(a)===i){let f=o;return{value:s.function("Multiply",[s.function("Power",[s.number(2),f]),s.function("Factorial",[f])]),because:"even double factorial"}}}if(m(n,"Add")&&n.ops.length===2&&r.isSame(0)){let a=null,l=!1;for(let f of n.ops)T(f)===i?l=!0:new Set(f.unknowns).has(i)||(a=f);if(l&&a){let f=o.add(s.One).simplify();return{value:s.function("Pochhammer",[a,f]),because:"rising factorial (Pochhammer)"}}}if(r.isSame(0)){let a=null,l=!1;if(m(n,"Subtract")&&n.ops.length===2){let[f,c]=n.ops;T(c)===i&&!new Set(f.unknowns).has(i)&&(a=f,l=!0)}else if(m(n,"Add")&&n.ops.length===2)for(let f of n.ops)m(f,"Negate")&&T(f.op1)===i?l=!0:new Set(f.unknowns).has(i)||(a=f);if(l&&a){let f=o.add(s.One).simplify();return{value:s.function("Divide",[s.function("Factorial",[a]),s.function("Factorial",[a.sub(f)])]),because:"falling factorial"}}}if(m(n,"Multiply")){let a=[],l=[];for(let f of n.ops)new Set(f.unknowns).has(i)?l.push(f):a.push(f);if(a.length>0&&l.length>0){let f=a.length===1?a[0]:s.function("Multiply",a),c=l.length===1?l[0]:s.function("Multiply",l),p=o.sub(r).add(s.One).simplify(),d=s.function("Product",[c,t]);return{value:f.pow(p).mul(d),because:"factor out constant from product"}}}}var XU=new Set(["Arcsin","Arctan","Arccsc"]),KU=new Set(["Sinh","Tanh","Coth","Csch","Arsinh","Artanh","Arcoth","Arcsch"]),eZ=new Set(["Cos","Sec","Cosh","Sech"]);function jD(e){return e===void 0?e:e.because?.startsWith("|")?{...e,purpose:"transform"}:e}function zD(e){return jD(nZ(e))}function nZ(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 u=r.filter((l,f)=>f!==o),a=u.length===1?u[0]:t._fn("Multiply",u);return{value:s.mul(t._fn("Abs",[a])),because:"|xy| -> x|y| when x >= 0"}}if(s.isNonPositive===!0){let u=r.filter((l,f)=>f!==o),a=u.length===1?u[0]:t._fn("Multiply",u);return{value:s.neg().mul(t._fn("Abs",[a])),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((XU.has(i)||KU.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 JD(e){return jD(tZ(e))}function tZ(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 GD(e){let n=e.operator;if(!eZ.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 UD(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,u=o&&i.isPositive===!0,a=o&&i.isNegative===!0,l=s&&r.isPositive===!0,f=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(u){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(f){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(a){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,u=o&&i.isPositive===!0,a=o&&i.isNegative===!0;if(o&&s)return{value:t.NaN,because:"inf / inf -> NaN"};if(u){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(a){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(I(i,"PositiveInfinity"))return{value:t.PositiveInfinity,because:"exp(+inf) -> +inf"};if(I(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,u=o&&i.isPositive===!0,a=o&&i.isNegative===!0,l=s&&r.isPositive===!0,f=s&&r.isNegative===!0;if(I(i,"ExponentialE")&&l)return{value:t.PositiveInfinity,because:"e^(+inf) -> +inf"};if(I(i,"ExponentialE")&&f)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(f){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(u&&r.isNegative===!0)return{value:t.Zero,because:"+inf^negative -> 0"};if(a){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[c,p]=r.numeratorDenominator,d=c.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 ZD(e){let n=iZ(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 iZ(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)&&Yr(t,"Ln",r)!==!0)return{value:o.mul(t._fn("Ln",[r])),because:"ln(x^n) -> n*ln(x)"}}}if(m(i,"Power")&&T(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")&&T(o.op1)==="ExponentialE"){let s=o.op2,u=i.ops.filter((l,f)=>f!==r),a=u.length===1?u[0]:t._fn("Multiply",[...u]);return{value:s.add(t._fn("Ln",[a])),because:"ln(e^x * y) -> x + ln(y)"}}}if(m(i,"Divide")&&i.op1?.operator==="Power"&&m(i.op1)&&T(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)&&T(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||T(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(T(i)==="ExponentialE"&&T(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")&&T(i.op1)==="ExponentialE"&&!T(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&&!T(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,u=i.op2;if(s&&u){if(s.isNonNegative===!0||Rn(s)&&(u.isOdd===!0||u.isRational===!1)&&Yr(t,"Ln",s)!==!0)return{value:u.mul(t._fn("Log",[s,o])),because:"log_c(x^n) -> n*log_c(x)"};if(u.isEven===!0&&Rn(s))return{value:u.mul(t._fn("Log",[t._fn("Abs",[s]),o])),because:"log_c(x^n) -> n*log_c(|x|) when n even"};if(u.isRational===!0&&u.isInteger===!1&&Rn(s)){let a=u.json;if(Array.isArray(a)&&a[0]==="Rational"){let l=a[1];return a[2]%2===0||l%2!==0?{value:u.mul(t._fn("Log",[s,o])),because:"log_c(x^{p/q}) -> (p/q)*log_c(x)"}:{value:u.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 u=i.ops[s];if(m(u,"Power")&&u.op1?.isSame(o)){let a=u.op2,l=i.ops.filter((c,p)=>p!==s),f=l.length===1?l[0]:t._fn("Multiply",[...l]);return{value:a.add(t._fn("Log",[f,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,u=i.op2;if(s.isPositive===!0&&u.isPositive===!0){let a=T(o)==="Nothing",l=a?t._fn("Log",[s]):t._fn("Log",[s,o]),f=a?t._fn("Log",[u]):t._fn("Log",[u,o]);return{value:l.sub(f),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(T(i)==="ExponentialE"&&r.operator==="Ln"&&m(r))return{value:r.op1,because:"e^ln(x) -> x"};if(T(i)==="ExponentialE"&&r.operator==="Log"&&m(r)&&r.op1){let o=r.op2;if(!o||T(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&&T(o)!=="ExponentialE")return{value:r.op1.pow(t.One.div(t._fn("Ln",[o]))),because:"e^log_c(x) -> x^{1/ln(c)}"}}if(T(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 u=r.ops.filter((l,f)=>f!==o),a=u.length===0?t.Zero:u.length===1?u[0]:t._fn("Add",[...u]);return{value:s.op1.mul(t._fn("Exp",[a])),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 u=r.ops.filter((p,d)=>d!==o),a=u.length===0?t.Zero:u.length===1?u[0]:t._fn("Add",[...u]),l=s.op2;return{value:(!l||T(l)==="Nothing"||l.isSame(10)?s.op1.pow(t.One.div(t._fn("Ln",[t.number(10)]))):T(l)==="ExponentialE"?s.op1:s.op1.pow(t.One.div(t._fn("Ln",[l])))).mul(i.pow(a)),because:"e^(log_c(x) + y) -> x^{1/ln(c)} * e^y"}}}if(T(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 u=r.ops.filter((l,f)=>f!==o),a=u.length===1?u[0]:t._fn("Multiply",[...u]);return{value:s.op1.pow(a),because:"e^(ln(x) * y) -> x^y"}}}if(T(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 u=r.ops.filter((l,f)=>f!==o),a=u.length===0?t.Zero:u.length===1?u[0]:t._fn("Add",[...u]);return{value:s.op1.mul(i.pow(a)),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 u=r.ops.filter((l,f)=>f!==o),a=u.length===1?u[0]:t._fn("Multiply",[...u]);return{value:s.op1.pow(a),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 u=s.op1;if(m(u,"Ln")&&u.op1)i.push({index:o,arg:u.op1,positive:!1});else if(m(u,"Log")&&u.op1&&u.op2){let a=JSON.stringify(u.op2.json);r.has(a)||r.set(a,[]),r.get(a).push({index:o,arg:u.op1,base:u.op2,positive:!1})}}else if(m(s,"Log")&&s.op1&&s.op2){let u=JSON.stringify(s.op2.json);r.has(u)||r.set(u,[]),r.get(u).push({index:o,arg:s.op1,base:s.op2,positive:!0})}}if(i.length>=2&&!i.some(o=>Yr(t,"Ln",o.arg)===!0||!Rn(o.arg))){let o=t.One,s=t.One;for(let f of i)f.positive?o=o.mul(f.arg):s=s.mul(f.arg);let u=o.div(s),a=new Set(i.map(f=>f.index)),l=[...e.ops].filter((f,c)=>!a.has(c));return l.length===0?{value:t._fn("Ln",[u]),because:"combine ln terms"}:{value:t._fn("Add",[t._fn("Ln",[u]),...l]),because:"combine ln terms"}}for(let[,o]of r)if(o.length>=2&&!o.some(s=>Yr(t,"Ln",s.arg)===!0||!Rn(s.arg))){let s=t.One,u=t.One;for(let g of o)g.positive?s=s.mul(g.arg):u=u.mul(g.arg);let a=s.div(u),l=new Set(o.map(g=>g.index)),f=[...e.ops].filter((g,h)=>!l.has(h)),c=o[0].base,d=T(c)==="Nothing"?t._fn("Log",[a]):t._fn("Log",[a,c]);return f.length===0?{value:d,because:"combine log terms"}:{value:t._fn("Add",[d,...f]),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 u=o.re,a=s.re;if(Number.isFinite(u)&&Number.isFinite(a)&&a>1&&u>0){let l=H(o),f=H(s);if(l!==null&&f!==null&&f>1n){let c=Math.log(u)/Math.log(a),p=Math.round(c);for(let d of[p-1,p,p+1])if(!(d<0)&&f**BigInt(d)===l)return{value:t.number(d),because:"ln(a)/ln(b) -> k when a = b^k"}}}}}}}}}function rZ(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 a=s?t:i,f=(s?i:t).numericValue;if(!(f instanceof Se)||f.im!==0)return;let c=f.radical;if(!Number.isInteger(c)||c<=1)return;let p=Number(f.rational[0]),d=Number(f.rational[1]),g=Ie(a),h=Number(g[0])/Number(g[1]);if(!(h>0))return;let b=n.number([p*p*c,d*d]),y=a.mul(a).sub(b),x=y.re;if(x===null||x<0)return;let v=y.sqrt();if(!Ie(v))return;let S=n.number([1,2]),_=a.add(v).mul(S),w=a.sub(v).mul(S),M=_.re,A=w.re;if(M===null||A===null||M<0||A<0)return;let k=p*d<0?-1:1,D=n.function("Sqrt",[_]),q=n.function("Sqrt",[w]),O=n.function("Add",[D,k<0?n.function("Negate",[q]):q]),j=h+p/d*Math.sqrt(c),G=Math.sqrt(M)+k*Math.sqrt(A);if(G>=0&&!(Math.abs(G*G-j)>1e-9*(1+Math.abs(j))))return O}function oZ(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 Se)||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,u]=i,a=o*s*u,l=Math.sqrt(a);if(!Number.isInteger(l))return;let f=i.map(h=>n.number([l,h])),c=f.reduce((h,b)=>h+(b.re??NaN),0);if(!Number.isFinite(c)||Math.abs(c-r)>1e-9*(1+r))return;let p=n.function("Add",f.map(h=>n.function("Sqrt",[h]))),d=r+2*(Math.sqrt(o)+Math.sqrt(s)+Math.sqrt(u)),g=p.N().re;if(!(g===null||!(g>=0))&&!(Math.abs(g*g-d)>1e-9*(1+Math.abs(d))))return p}function sZ(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,u=s===t?i:s===i?t:void 0;if(!s||!u)return;let a=Ie(s),l=u.numericValue;if(!a||a[1]!==1||!(l instanceof Se)||l.im!==0||l.rational[1]!==1||!Number.isInteger(l.radical)||l.radical<=1)return;let f=Number(a[0]),c=Number(l.rational[0]),p=l.radical;if(![f,c,p].every(Number.isSafeInteger))return;let d=f*f-c*c*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(f)+Math.abs(c)*Math.sqrt(p)))+2);for(let b=-h;b<=h;b++){if(4*b*b*b-3*g*b!==f)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 v of x===0?[0]:[x,-x])if(v*(3*b*b+v*v*p)===c)return n.function("Add",[n.number(b),n.function("Multiply",[n.number(v),n.function("Sqrt",[n.number(p)])])])}}}function HD(e){if(!N(e))return!1;if(Ie(e))return!0;let n=e.numericValue;return n instanceof Se&&n.im===0}function YD(e){if(!N(e))return!1;let n=e.numericValue;return n instanceof Se&&n.im===0&&n.radical>1}function n2(e){if(m(e,"Sqrt")&&e.op1)return e.op1;if(N(e)){let n=e.numericValue;if(n instanceof Se&&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 uZ(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(!HD(r)||!HD(o)||!YD(r)&&!YD(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 u=n.function("Add",[r,o.neg()]),a=m(u,"Add")?u.ops:[u],l=m(t,"Add")?t.ops:[t],f=[];for(let h of l)for(let b of a)f.push(h.mul(b));let c=n.function("Add",f),p=n.function("Divide",[c,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 t2(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=sZ(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=n2(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,u=i.op2;return{value:s.pow(t.One.div(u.mul(r))),because:"root(root(x, m), n) -> x^{1/(m*n)}"}}if(m(i,"Power")){let s=i.op1,u=i.op2;if(s&&u?.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&&u){let a=u.div(r);if(r.isEven===!0){if(a.isInteger===!0)return{value:t._fn("Abs",[s]).pow(a),because:"root(x^m, n) -> |x|^{m/n} when m/n is integer"};let l=Ie(a);if(l){let[,f]=l,c=Ie(r);if(c&&Number(f)<Number(c[0]))return{value:t._fn("Abs",[s]).pow(a),because:"root(x^m, n) -> |x|^{m/n}"}}}if(r.isOdd===!0&&u.isInteger===!0)return{value:s.pow(a),because:"root(x^m, n) -> x^{m/n} when n is odd"};if(s.isNonNegative===!0&&a.isInteger===!0)return{value:s.pow(a),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 u=[],a=[];for(let l of i.ops){let f=t._fn("Root",[l,r]),c=t2(f);if(c&&!c.value.isSame(f))a.push(c.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){a.push(t.number(d));continue}}u.push(l)}}if(a.length>0){let l=a.length===1?a[0]:t._fn("Multiply",a);if(u.length===0)return{value:l,because:"root(product, n) -> factored"};let f=u.length===1?u[0]:t._fn("Multiply",u);return{value:t._fn("Multiply",[l,t._fn("Root",[f,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=Wg(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=Qg(i);if(s!==null)return{value:t._fn("Sqrt",[s]),because:"sqrt(a\xB2-b\xB2) -> sqrt((a-b)(a+b))"};let u=rZ(i);if(u!==void 0)return{value:u,because:"denest \u221A(a+b\u221Ac) -> \u221Ax+\u221Ay"};let a=oZ(i);if(a!==void 0)return{value:a,because:"denest \u221A(a+2\u221Ap+2\u221Aq+2\u221Ar) -> \u221Ax+\u221Ay+\u221Az"}}let r=n2(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 u=s.sub(t.One).div(2);if(u.isPositive===!0)return{value:t._fn("Abs",[o]).pow(u).mul(t._fn("Sqrt",[o])),because:"sqrt(x^{2n+1}) -> |x|^n * sqrt(x)"}}}}}if(m(i,"Multiply")){let o=[],s=[];for(let u of i.ops)if(m(u,"Power")&&u.op1&&u.op2&&Rn(u.op1)){let a=u.op1,l=u.op2;if(l.isSame(2))o.push(t._fn("Abs",[a]));else if(l.isEven===!0&&l.isPositive===!0)o.push(t._fn("Abs",[a]).pow(l.div(2)));else if(l.isInteger===!0&&l.isPositive===!0&&l.isOdd===!0){let f=l.sub(t.One).div(2);f.isPositive===!0&&o.push(t._fn("Abs",[a]).pow(f)),s.push(a)}else s.push(u)}else s.push(u);if(o.length>0){let u=o.length===1?o[0]:t._fn("Multiply",o);if(s.length===0)return{value:u,because:"sqrt(a^2 * ...) -> |a| * ..."};let a=s.length===1?s[0]:t._fn("Multiply",s);return{value:u.mul(t._fn("Sqrt",[a])),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[u,a]=s,l=Number(u),f=Number(a);if(l%2!==0&&f%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[u,a]=s,l=Number(u),f=Number(a),c=l%2!==0,p=f%2!==0;if(c&&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,v)=>v===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(u=>u.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 u=Ie(r);if(u){let[a,l]=u,f=Number(a),c=Number(l),p=f%2===0,d=f%2!==0,g=c%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=n2(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,u=i.op2,a=r.div(u);if(a.isInteger===!0||s.isNonNegative===!0)return{value:s.pow(a),because:"root(x, k)^n -> x^{n/k}"}}if(m(i,"Power")){let s=i.op1,u=i.op2;if(s&&u){let a=s.isNonNegative===!0,l=r.isInteger===!0;if(a||l)return{value:s.pow(u.mul(r)),because:"(x^n)^m -> x^{n*m}"}}}if(m(i,"Divide")&&i.op2.isSame(0)===!1){let s=i.op1,u=i.op2;if(m(r,"Negate"))return{value:u.div(s).pow(r.op1),because:"(a/b)^{-n} -> (b/a)^n"};if(r.isSame(-1))return{value:u.div(s),because:"(a/b)^{-1} -> b/a"};if(r.isNegative===!0&&N(r))return{value:u.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=uZ(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,u=i.op2,a=r.op1,l=r.op2;if(s?.isSame(a)&&u&&l){let f=t.function("Add",[u,l.neg()]);return{value:s.pow(f),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,u=r.op2;if(m(u,"Negate"))return{value:i.mul(s.pow(u.op1)),because:"a / b^{-n} -> a * b^n"}}if(m(r,"Multiply"))for(let s=0;s<r.ops.length;s++){let u=r.ops[s];if(m(u,"Power")&&u.op1.isSame(0)===!1&&u.op2.operator==="Negate"&&m(u.op2)){let a=u.op1,l=u.op2.op1,f=r.ops.filter((p,d)=>d!==s),c=f.length===1?f[0]:t._fn("Multiply",f);return{value:i.div(c).mul(a.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,u=r.op1.op2,a=r.op2;return{value:i.mul(u.div(s).pow(a)),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,u=r.op1,a=r.op2;if(o?.isSame(u)&&s&&a){let l=t.function("Add",[s,a]);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 WD=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]),aZ=new Set(["Sin","Tan","Cot","Csc"]),lZ=new Set(["Cos","Sec"]),QD={Sin:"Cos",Cos:"Sin",Tan:"Cot",Cot:"Tan",Sec:"Csc",Csc:"Sec"},fZ={Sin:-1,Cos:-1,Tan:1,Cot:1,Sec:-1,Csc:-1},cZ={Sin:1,Cos:-1,Tan:-1,Cot:-1,Sec:-1,Csc:1},pZ={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 dZ(e,n){if(T(e)==="Pi"||m(e,"Negate")&&T(e.op1)==="Pi")return null;if(m(e,"Multiply")){let t=e.ops.findIndex(o=>T(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 mZ(e){if(!e)return!1;if(m(e,"Divide")&&T(e.op1)==="Pi"&&e.op2?.isSame(2))return!0;if(m(e,"Multiply")&&e.nops===2){let t=(T(e.op1)==="Pi"?e.op2:T(e.op2)==="Pi"?e.op1:void 0)?.re;return typeof t=="number"&&Math.abs(t-.5)<1e-10}return!1}var gZ=new Set(["Arcsin","Arccos","Arctan","Arccot","Arcsec","Arccsc"]);function hZ(e,n,t){if(!m(n,"Add"))return null;let i=n.ops,r=null,o=-1;for(let f=0;f<i.length;f++){let c=i[f];if(T(c)==="Pi"){r=1,o=f;break}if(m(c,"Multiply")){let p=c.ops,d=p.findIndex(g=>T(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=f;break}}}else if(g.length===0){r=1,o=f;break}}}if(m(c,"Negate")&&T(c.op1)==="Pi"){r=-1,o=f;break}}if(r===null||o<0)return null;let s=e==="Tan"||e==="Cot"?1:2,u=r%s;u<0&&(u+=s);let a=i.filter((f,c)=>c!==o);if(u!==0&&(u===1?a.push(t.Pi):a.push(t.expr(["Multiply",u,"Pi"]))),u===r%s&&u===r)return null;let l;return a.length===0?l=t.Zero:a.length===1?l=a[0]:l=te(...a),t.expr([e,l])}function XD(e){let n=e.operator,t=e.engine;if(WD.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(aZ.has(n))return{value:t._fn(n,[r]).neg(),because:`${n}(-x) -> -${n}(x)`};if(lZ.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(T(r)==="Pi"&&o){let s=cZ[n];if(s!==void 0){let u=t._fn(n,[o]);return{value:s===1?u:u.neg(),because:`${n}(\u03C0 - x) -> ${s===1?"":"-"}${n}(x)`}}}}if(m(i,"Add")){let r=i.ops.findIndex(o=>T(o)==="Pi");if(r>=0){let o=i.ops.filter((s,u)=>u!==r);if(o.length===i.ops.length-1){let s=o.length===1?o[0]:t._fn("Add",o),u=fZ[n];if(u!==void 0){let a=t._fn(n,[s]);return{value:u===1?a:a.neg(),because:`${n}(\u03C0 + x) -> ${u===1?"":"-"}${n}(x)`}}}}}if(m(i,"Subtract")){let r=i.op1,o=i.op2,s=!1;if(m(r,"Divide")&&T(r.op1)==="Pi"&&r.op2?.isSame(2)&&(s=!0),s&&o){let u=QD[n];if(u)return{value:t._fn(u,[o]),because:`${n}(\u03C0/2 - x) -> ${u}(x)`}}}if(m(i,"Add")&&i.nops===2){let r=i.ops,o=null,s=null;for(let u of r){if(m(u,"Multiply")&&u.nops===2){let[a,l]=[u.op1,u.op2];if(T(l)==="Pi"){let f=a?.re;typeof f=="number"&&Math.abs(f-.5)<1e-10&&(o=u)}}m(u,"Negate")&&u.op1&&(s=u.op1)}if(o&&s){let u=QD[n];if(u)return{value:t._fn(u,[s]),because:`${n}(\u03C0/2 - x) -> ${u}(x)`}}}if(m(i,"Add")){let r=i.ops.findIndex(o=>mZ(o));if(r>=0){let o=pZ[n];if(o){let s=i.ops.filter((u,a)=>a!==r);if(s.length>0){let u=s.length===1?s[0]:t._fn("Add",s),a=t._fn(o.fn,[u]);return{value:o.sign===1?a:a.neg(),because:`${n}(\u03B8 + \u03C0/2) -> ${o.sign===1?"":"-"}${o.fn}(\u03B8)`}}}}}if(n==="Sin"||n==="Cos"){let r=dZ(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=hZ(n,i,t);if(r)return{value:r,because:`${n} periodicity reduction`}}}if(gZ.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,u=r.op1;if(s?.isSame(u)){let a=t._fn("Sin",[s.mul(2)]);if(o.length===0)return{value:a.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:a,because:"2*sin(x)*cos(x) -> sin(2x)"}:{value:l.mul(a).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 f=l.op1;if(m(f)&&WD.has(f.operator)&&f.op1)return{fn:f.operator,arg:f.op1}}return null},o=(l,f,c,p)=>{let d=i.filter((g,h)=>h!==l&&h!==f);return d.length===0?{value:c,because:p}:{value:t._fn("Add",[c,...d]),because:p}};for(let l=0;l<i.length;l++){let f=r(i[l]);if(!f||f.fn!=="Sin"&&f.fn!=="Cos")continue;let c=f.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!==c||!d.arg.isSame(f.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[f,c]=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(c,f)??p(f,c)};for(let l=0;l<i.length;l++){let f=s(i[l]);if(!f)continue;let c=f.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!==c||!d.arg.isSame(f.arg)||!d.coeff.isSame(f.coeff)))return o(l,p,f.coeff,"a*sin\xB2(x) + a*cos\xB2(x) -> a")}}let u=l=>{let f=m(l,"Multiply")?l.ops:[l],c=[];for(let p=0;p<f.length;p++){let d=f[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=f.filter((v,S)=>S!==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);c.push({fn:g.operator,arg:g.op1,rest:x})}return c};for(let l=0;l<i.length;l++){let f=u(i[l]);if(f.length!==0)for(let c=0;c<i.length;c++){if(c===l)continue;let p=u(i[c]);if(p.length!==0)for(let d of f){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,c,d.rest,"g*sin\xB2(x) + g*cos\xB2(x) -> g")}}}let a=i.findIndex(l=>l.isSame(1));if(a>=0)for(let l=0;l<i.length;l++){if(l===a)continue;let f=r(i[l]);if(f){if(f.fn==="Tan")return o(l,a,t._fn("Sec",[f.arg]).pow(2),"tan\xB2(x) + 1 -> sec\xB2(x)");if(f.fn==="Cot")return o(l,a,t._fn("Csc",[f.arg]).pow(2),"1 + cot\xB2(x) -> csc\xB2(x)")}}}if(n==="Add"&&m(e)&&e.ops.length===2){let i=s=>{let u=1;for(;m(s,"Negate")&&s.op1;)u=-u,s=s.op1;if(!m(s,"Multiply"))return null;let a,l;for(let f of s.ops){if(N(f)){if(f.isSame(1))continue;if(f.isSame(-1)){u=-u;continue}return null}if(m(f,"Sin")&&f.op1&&a===void 0)a=f.op1;else if(m(f,"Cos")&&f.op1&&l===void 0)l=f.op1;else return null}return a===void 0||l===void 0?null:{sign:u,sinArg:a,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 u=t._fn("Sin",[r.sinArg.add(r.cosArg)]);return{value:r.sign===1?u:u.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 c=s.op1;if(m(c,"Sin"))return{value:t._fn("Cos",[c.op1]).pow(2),because:"1 - sin\xB2(x) -> cos\xB2(x)"};if(m(c,"Cos"))return{value:t._fn("Sin",[c.op1]).pow(2),because:"1 - cos\xB2(x) -> sin\xB2(x)"}}let u=null,a=null;if(i.isSame(-1)&&m(r,"Power")&&r.op2?.isSame(2)?(u=i,a=r):r.isSame(-1)&&m(i,"Power")&&i.op2?.isSame(2)&&(u=r,a=i),u&&m(a)){let c=a.op1;if(m(c,"Sin"))return{value:t._fn("Cos",[c.op1]).pow(2).neg(),because:"sin\xB2(x) - 1 -> -cos\xB2(x)"};if(m(c,"Cos"))return{value:t._fn("Sin",[c.op1]).pow(2).neg(),because:"cos\xB2(x) - 1 -> -sin\xB2(x)"};if(m(c,"Sec"))return{value:t._fn("Tan",[c.op1]).pow(2),because:"sec\xB2(x) - 1 -> tan\xB2(x)"};if(m(c,"Csc"))return{value:t._fn("Cot",[c.op1]).pow(2),because:"csc\xB2(x) - 1 -> cot\xB2(x)"}}let l=null,f=null;if(m(i,"Negate")&&i.op1?.isSame(1)&&m(r)&&r.operator==="Power"&&r.op2?.isSame(2)?(l=i,f=r):m(r,"Negate")&&r.op1?.isSame(1)&&m(i)&&i.operator==="Power"&&i.op2?.isSame(2)&&(l=r,f=i),l&&m(f)){let c=f.op1;if(m(c,"Sec"))return{value:t._fn("Tan",[c.op1]).pow(2),because:"sec\xB2(x) - 1 -> tan\xB2(x)"};if(m(c,"Csc"))return{value:t._fn("Cot",[c.op1]).pow(2),because:"csc\xB2(x) - 1 -> cot\xB2(x)"}}if(m(i,"Negate")&&m(r)&&r.operator==="Negate"){let c=i.op1,p=r.op1;if(m(c,"Power")&&c.op2?.isSame(2)&&m(p)&&p.operator==="Power"&&p.op2?.isSame(2)){let d=c.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 bZ=new Set(["Sinh","Cosh","Tanh","Coth","Sech","Csch"]),yZ=new Set(["Sinh","Tanh","Coth","Csch"]),xZ=new Set(["Cosh","Sech"]),vZ=new Set(["Arsinh","Arcosh","Artanh","Arcoth","Arsech","Arcsch"]);function KD(e){let n=e.operator,t=e.engine;if(bZ.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(yZ.has(n))return{value:t._fn(n,[r]).neg(),because:`${n}(-x) -> -${n}(x)`};if(xZ.has(n))return{value:t._fn(n,[r]),because:`${n}(-x) -> ${n}(x)`}}}}if(vZ.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 Ku(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 e4(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=Ku(n),o=Ku(t);if(r&&o&&r.base.isSame(o.base)&&r.offset-o.offset===1)return{value:n,because:"C(n,n-1) -> n"}}function n4(e){if(!m(e,"Factorial2"))return;let n=e.op1;if(!n||N(n))return;let t=e.engine,i=Ku(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 EZ(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,u)=>u!==t);return o.length===1&&N(o[0])&&Number.isInteger(o[0].re)?{coeff:o[0].re,factArg:r}:null}return null}function t4(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=EZ(n[h]);b&&t.push({...b,index:h})}if(t.length<2)return;let i=e.engine,o=t.map(h=>({...h,bo:Ku(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 u=1/0;for(let h of o)h.bo.offset<u&&(u=h.bo.offset);let a=o.find(h=>h.bo.offset===u).factArg,l=[];for(let h of o){let b=h.bo.offset-u;if(b===0)l.push(i.number(h.coeff));else if(b>0&&b<=8){let y=a.add(i.One);for(let x=2;x<=b;x++)y=y.mul(a.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 f=l.length===1?l[0]:i.function("Add",l),c=i._fn("Factorial",[a]),p=i._fn("Multiply",[c,f]),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 i4(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,u;if(m(n,"Power")?(r=n.op1,o=n.op2):(r=n,o=i.One),m(t,"Power")?(s=t.op1,u=t.op2):(s=t,u=i.One),r&&s&&r.isSame(s)&&(!Ie(o)||!Ie(u))){let a=i.function("Add",[o,u.neg()]);return a.isSame(0)?{value:i.One,because:"x^a/x^a -> 1"}:a.isSame(1)?{value:r,because:"x^a/x^b -> x when a-b=1"}:{value:i._fn("Power",[r,a]),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 a=BigInt(Math.trunc(r.re)),l=BigInt(Math.trunc(o.re));if((a>l?a-l:l-a)>1000n)return;if(a>=l){let c=1n;for(let p=l+1n;p<=a;p++)c*=p;return{value:i.number(c),because:"n!/k! partial product"}}else{let c=1n;for(let p=a+1n;p<=l;p++)c*=p;return{value:i.number([1n,c]),because:"n!/k! -> 1/(partial product)"}}}let s=Ku(r),u=Ku(o);if(s&&u&&s.base.isSame(u.base)){let a=s.offset-u.offset;if(Number.isInteger(a)&&a>=1&&a<=8){let l=o.add(i.One);for(let f=2;f<=a;f++)l=l.mul(o.add(i.number(f)));return{value:l,because:"n!/k! -> (k+1)..n"}}if(Number.isInteger(a)&&a<=-1&&a>=-8){let l=r.add(i.One);for(let f=2;f<=-a;f++)l=l.mul(r.add(i.number(f)));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(u=>m(u,"Factorial")),s=t.ops.filter(u=>!m(u,"Factorial"));if(o.length===2&&s.length===0&&m(o[0])&&m(o[1])){let u=o[0].op1,a=o[1].op1;if(N(r)&&N(u)&&N(a)&&u.re+a.re===r.re){let f=u.re<=a.re?u:a;return{value:i._fn("Binomial",[r,f]),because:"n!/(k!(n-k)!) -> Binomial"}}if(u.add(a).isSame(r))return{value:i._fn("Binomial",[r,u]),because:"n!/(k!(n-k)!) -> Binomial"}}}}var r4=[{match:{sym:"GoldenRatio"},replace:["Divide",["Add",1,["Sqrt",5]],2]},_Z,SZ,e=>{if(e.operator!=="Divide")return;let n=e.unknowns;if(n.length!==1)return;let t=n[0],i=Ua(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=$u(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=Ss(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):I(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=Ae(e);return n?{value:n,because:"expand"}:void 0},t4,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):I(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 u=i.operator==="Sin"||r.operator==="Sin",a=i.operator==="Cos"||r.operator==="Cos";if(u&&a)return;let l=i.operator==="Tan"||r.operator==="Tan",f=i.operator==="Cot"||r.operator==="Cot";if(l&&f)return}if(!(n.some(i=>i.operator==="Factorial")&&n.some(i=>i.operator==="Add")))return{value:ge(...n.map(i=>{let r=i.canonical;if(r.unknowns.length===0&&m(r)){if(r.operator==="Power"&&(T(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 i2(He(i))?{value:i,because:"sqrt"}:i2(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<ve&&t.re<ve){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(i2(He(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"}},qD,VD,e=>{if(!HE(e)||!m(e))return;let n=Rp(e.operator,e.op1);if(n)return{value:n,because:"constructible value"}},e=>{if(!m(e,"InverseFunction"))return;let n=kp(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"}}}},BD,zD,JD,GD,UD,ZD,t2,XD,KD,i4,e4,n4,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 u,a;if(m(s,"Power"))u=s.op1,a=s.op2;else if(I(s))u=s,a=n.One;else{i.push(s);continue}let l=JSON.stringify(u.json),f=t.get(l);f||(f={base:u,terms:[]},t.set(l,f)),f.terms.push({term:s,exp:a})}let r=!1;for(let s=i.length-1;s>=0;s--){let u=i[s];if(N(u)){let c=u.numericValue;if(c instanceof Se&&c.radical>1){let p=c.rational,d=Number(p[0]),g=Number(p[1]),h=new Map,b=di(c.radical);for(let[v,S]of Object.entries(b)){if(v==="1")continue;let _=Number(v),[w,M]=h.get(_)??[0,1];h.set(_,[w*2+S*M,M*2])}let y=Math.abs(d);if(y>1){let v=di(y);for(let[S,_]of Object.entries(v)){if(S==="1")continue;let w=Number(S),[M,A]=h.get(w)??[0,1];h.set(w,[M+_*A,A])}}if(g>1){let v=di(g);for(let[S,_]of Object.entries(v)){if(S==="1")continue;let w=Number(S),[M,A]=h.get(w)??[0,1];h.set(w,[M-_*A,A])}}if(h.size>0&&[...h.keys()].every(v=>t.has(JSON.stringify(n.number(v).json)))){for(let[v,[S,_]]of h){let w=JSON.stringify(n.number(v).json),M=t.get(w),A=Dn(Math.abs(S),_),k=S/A,D=_/A;M.terms.push({term:u,exp:D===1?n.number(k):n.number([k,D])})}i.splice(s,1),d<0&&i.push(n.NegativeOne),r=!0;continue}}}if(!N(u))continue;let a=u.re;if(Number.isInteger(a)&&Math.abs(a)>1){let c=Math.abs(a),p=di(c),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:u,exp:n.number(h)})}i.splice(s,1),a<0&&i.push(n.NegativeOne),r=!0;continue}}let l=u.numerator?.re,f=u.denominator?.re;if(l!==void 0&&f!==void 0&&Number.isFinite(l)&&Number.isFinite(f)&&Number.isInteger(l)&&Number.isInteger(f)&&f>1){let c=Math.abs(l),p=c>1?di(c):{},d=di(f),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,v=JSON.stringify(n.number(b).json);t.get(v).terms.push({term:u,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 u=s.base;if(u.isPositive===!0||u.isNegative===!0||N(u))r=!0;else{let l=s.terms.map(c=>c.exp);if(n.function("Add",l).isPositive===!0)r=!0;else{for(let c of s.terms)i.push(c.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 u=s.terms.map(l=>l.exp),a=n.function("Add",u);a.isSame(0)?o.push(n.One):a.isSame(1)?o.push(s.base):o.push(n._fn("Power",[s.base,a]))}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 i2(e){return e===void 0?!1:typeof e=="number"?Number.isInteger(e):e.isExact}function _Z(e){let n=e.operator;if(!Xi(n)&&!du(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=Lu(e)??e,dt(e.operator),m(e)&&e.nops===2&&!e.op2.isSame(0)){let s=Lu(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 SZ(e){if(!m(e,"List")||!e.ops.every(i=>du(i.operator)||Xi(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 a4(e,n){return ru(n,e.context.lexicalScope)}function NZ(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 IZ(e){let n=fe(e)?e.operator.description:ie(e)?e.value.description:void 0;return n?typeof n=="string"?[n]:n:[]}function wZ(e){return(fe(e)?e.operator.keywords:ie(e)?e.value.keywords:void 0)??[]}function l4(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 u=new Map,a=e.latexSyntax?.getNamedTriggers?.();if(a)for(let{name:p,triggers:d}of a)u.set(p,d);let l=[],f=new Set,c=e.context.lexicalScope;for(;c;){for(let[p,d]of c.bindings){if(f.has(p))continue;f.add(p);let g=NZ(d);if(g===void 0)continue;let h=p.toLowerCase(),b=(u.get(p)??[]).map(M=>M.toLowerCase()),y=IZ(d).map(M=>M.toLowerCase()),x=wZ(d).map(M=>M.toLowerCase()),v=[h,...b,...x,...y],S=M=>{if(h===M)return 0;if(h.startsWith(M))return 1;if(b.some(A=>A===M)||x.some(A=>A===M))return 2;if(h.includes(M))return 3;if(b.some(A=>A.includes(M)))return 4;if(v.some(A=>A.includes(M)))return 5},_=r.filter(M=>S(M)!==void 0).length;if(_===0)continue;let w=1/0;for(let M of o){let A=S(M);A!==void 0&&A<w&&(w=A)}l.push({id:p,kind:g,matched:_,tier:w})}c=c.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 o4=new WeakMap;function TZ(e){let n=o4.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 o4.set(e,{generation:e._generation,names:t}),t}function f4(e,n){if(!n)return;let t=TZ(e),i=n.toLowerCase(),r=a=>{let l=a.toLowerCase(),f=0;for(;f<i.length&&f<l.length&&i[f]===l[f];)f+=1;return f},o=a=>{if(a.length!==0)return a.sort((l,f)=>{let c=r(l),p=r(f);return c!==p?p-c:l.length!==f.length?l.length-f.length:l<f?-1:l>f?1:0})[0]},s=t.filter(a=>a!==n&&a.toLowerCase()===i);if(s.length>0)return o(s);let u=[];for(let a of t){let l=a.toLowerCase();(l===`${i}s`||i.endsWith("s")&&l===i.slice(0,-1))&&u.push(a)}if(u.length>0)return o(u);if(n.length>=5){let a=n.length>=6?2:1,l=a+1,f=[];for(let c of t){if(c===n)continue;let p=My(i,c.toLowerCase(),a);p>a||(p<l?(l=p,f=[c]):p===l&&f.push(c))}if(f.length>0)return o(f)}if(n.length>=3){let a=t.filter(l=>l!==n&&l.toLowerCase().startsWith(i));if(a.length===1)return a[0]}}function c4(e,n,t,i){i??=e.context.lexicalScope,i.bindings.set(n,{value:new nr(e,n,{type:"unknown",inferred:!0})});let r=i.bindings.get(n);return xi(e,n,r,t),e._generation+=1,r}function p4(e,n,t,i){i??=e.context.lexicalScope,i.bindings.set(n,{value:new nr(e,n,{type:"function"})});let r=i.bindings.get(n);return xi(e,n,r,t),e._generation+=1,r}function d4(e,n){let t=ru(n,e.context.lexicalScope);if(!(!t||!ie(t)))return t.value.value}function m4(e,n,t){typeof t=="number"?t=e.number(t):typeof t=="boolean"&&(t=t?e.True:e.False);let i=ru(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 g4(e,n,t,{alias:i}={}){if(!sN(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 h4(e,n,t,i){if(typeof n!="string"){for(let[a,l]of Object.entries(n))e.declare(a,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||!An(r))throw new Error(`Invalid symbol "${r}": ${yi(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 u=t;if(ec(u)){let a=u;if(u.type!==void 0&&m(u.value,"Function")){let l=u.type instanceof Z?u.type.type:Y(u.type);la(l)!==void 0&&(r2(r,u.value,l,e.type(l).toString()),a={...u,value:o2(e,u.value,l)})}return e._declareSymbolValue(r,a,i),e}if(Kf(u))return e._declareSymbolOperator(r,u,i),e;{let a=Y(u,e._typeResolver);if(!po(a))throw Error([`Invalid argument for "${r}"`,JSON.stringify(u,void 0,4),"Use a type, a `OperatorDefinition` or a `ValueDefinition`"].join(`
|
|
134
134
|
| `));e._declareSymbolValue(r,{type:a},i)}return e}function b4(e,n,t){if(typeof n=="object"){for(let[u,a]of Object.entries(n))e.assign(u,a);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"&&la(r.value.type.type)!==void 0){let u=Ve(e.expr(t));if(u!==void 0){let a=r.value.type;r2(i,u,a.type,a.toString());let l=o2(e,u,a.type);if(!l.type.matches(a))throw new Error([`Symbol "${i}"`,`The value "${l.toString()}" of type "${l.type}" is not compatible with the type "${a}"`].join(`
|
|
@@ -137,12 +137,12 @@ Error in definition of "${i}"`,"",JSON.stringify(r,void 0,4),"",o instanceof Err
|
|
|
137
137
|
| `))}function o2(e,n,t){if(!m(n,"Function"))return n;let i=bn(t);if(i===void 0||bf(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 Js="\x1B[0m";var s2="\x1B[30;1m";var u2="\x1B[34;1m";var a2="\x1B[36;1m";var sb="\x1B[1m";var Fp=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 y4(e,n,t){l2(e,n??{parent:e.context?.lexicalScope,bindings:new Map},t)}function x4(e){f2(e)}function l2(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 Fp(e.context?.assumptions??[])})}function f2(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 v4(e,n,t){if(!n)return t();e._evalContextStack.push({lexicalScope:n,name:"",assumptions:new Fp(e.context?.assumptions??[])});try{return t()}finally{e._evalContextStack.pop()?._assumptionsDirty&&(e._mutationGeneration+=1)}}function E4(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(`${sb}${u2}${i.name}${Js}`):console.groupCollapsed(`${sb}${u2}${i.name}${Js} ${s2}(${t})${Js}`);let r=[...i.assumptions.entries()].map(([o,s])=>`${o}: ${s}`);if(r.length>0){console.groupCollapsed(`${sb}${r.length} assumptions${Js}`);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(CZ(o,s));console.groupEnd(),t+=1}}function CZ(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=`${a2}${e}${Js}:${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=`${a2}${e}${Js}:${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(u=>`${s2}${u}${Js}`).join(" ");s.length>0&&(t+=`
|
|
138
138
|
\u2514 ${s}`)}else t="unknown";return t}function _4(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 c2(e){let n=e.operator;if(n==="Element")return FZ(e);if(n==="NotElement")return DZ(e);if(n==="Equal")return OZ(e);if(n==="NotEqual")return PZ(e);if(n==="And")return RZ(e);if(Xi(n))return m2(e);if(kZ.has(n))return"not-a-predicate";throw new Error("Unsupported assumption. Use `Element`, `NotElement`, `Equal`, `NotEqual`, `And` or an inequality")}var AZ={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}},kZ=new Set(["Or","Not","Implies","Equivalent","Xor","Nand","Nor","ForAll","Exists","ExistsUnique","ForElement"]);function RZ(e){if(e.operator,!m(e))return"not-a-predicate";let n=e.engine;n.pushScope();let t;try{t=S4(e)}finally{n.popScope()}return t==="contradiction"||t==="internal-error"?t:S4(e)}function S4(e){if(!m(e))return"not-a-predicate";let n=!1,t=!1;for(let i of e.ops){let r=c2(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 PZ(e){return e.operator,!m(e)||e.ops.length!==2?"not-a-predicate":p2(e.engine,e.op1,e.op2)}function p2(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(I(r,"True"))return"tautology";if(I(r,"False"))return"contradiction"}return e.context.assumptions.set(i,!0),"ok"}function DZ(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?d2(n,e.op1,t):"not-a-predicate"}function d2(e,n,t){let i=e.function("NotElement",[n,t]);if(!i.isValid)return"not-a-predicate";let r=I(n)?n.symbol:void 0;if(r===void 0||T4(e,r)){let o=i.evaluate();if(I(o,"True"))return"tautology";if(I(o,"False"))return"contradiction"}return e.context.assumptions.set(i,!0),"ok"}function OZ(e){e.operator;let n=e.unknowns;if(n.length===0){let o=e.evaluate();return I(o,"True")?"tautology":I(o,"False")?"contradiction":"not-a-predicate"}let t=e.engine;if(!m(e))return"not-a-predicate";let i=e.op1,r=I(i)?i.symbol:void 0;if(r&&!T4(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}),ub(t,r),"ok"):s.value.type&&!o.type.matches(s.value.type)&&!s.value.inferredType?"contradiction":(ub(t,r),t.context.lexicalScope.bindings.has(r)?(s.value.inferredType&&(s.value.type=_4(t,o)),t._setSymbolValue(r,o)):t.declare(r,{value:o}),"ok")}if(n.length===1){let o=n[0],s=rn(e,o),u=t.lookupDefinition(o);if(u&&ie(u)&&u.value.type&&!u.value.inferredType&&s.length>0&&!s.some(l=>!l.type||l.type.matches(u.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 a=s[0];return!u||!ie(u)?(t.declare(o,{value:a}),ub(t,o),"ok"):(ub(t,o),t.context.lexicalScope.bindings.has(o)?(u.value.inferredType&&(u.value.type=_4(t,a)),t._setSymbolValue(o,a)):t.declare(o,{value:a}),"ok")}return t.context.assumptions.set(e,!0),"ok"}function m2(e){let n=e.engine;if(!m(e))return"internal-error";if(e.ops.length>2){let f=e.ops,c=e.operator,p=!1;for(let d=0;d+1<f.length;d++){let g=m2(n.function(c,[f[d],f[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(I(s,"True"))return"tautology";if(I(s,"False"))return"contradiction";let u=s.unknowns;if(u.length===0)return"not-a-predicate";let a=m(s)?s.op1:void 0,l=a!==void 0?LZ(a):void 0;if(l!==void 0){let f=m0(s,l);if(f!==void 0){let p=it(n,l),d=$Z(p,f);if(d!==void 0)return d}let c=l.part==="abs"&&f!==void 0&&Wo(f.upper)!==void 0?"finite_number":"number";return qZ(n,l.symbol,c),n.context.assumptions.set(s,!0),l.part==="im"&&f!==void 0&&BZ(f)&&(d2(n,n.symbol(l.symbol),n.symbol("RealNumbers")),p2(n,n.symbol(l.symbol),n.Zero)),"ok"}if(u.length===1){let f=u[0],c=it(n,f),p=e.operator,d=e.op1,g=e.op2,h=I(d,f),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 v;if(p==="Greater"?v=h?"greater":"less":p==="GreaterEqual"?v=h?"greaterEqual":"lessEqual":p==="Less"?v=h?"less":"greater":v=h?"lessEqual":"greaterEqual",v==="greater"||v==="greaterEqual"){let S=v==="greater";if(c.lower!==void 0){let _=N(c.lower)?c.lower.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(S){if(_>x||c.lowerStrict&&_>=x)return"tautology"}else if(_>x||c.lowerStrict&&_>=x||!c.lowerStrict&&_>=x)return"tautology"}}if(c.upper!==void 0){let _=N(c.upper)?c.upper.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(S){if(_<x||c.upperStrict&&_<=x||!c.upperStrict&&_<=x)return"contradiction"}else if(_<x||c.upperStrict&&_<=x)return"contradiction"}}}else{let S=v==="less";if(c.upper!==void 0){let _=N(c.upper)?c.upper.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(S){if(_<x||c.upperStrict&&_<=x)return"tautology"}else if(_<x||_<=x)return"tautology"}}if(c.lower!==void 0){let _=N(c.lower)?c.lower.numericValue:void 0;if(typeof _=="number"&&isFinite(_)){if(S){if(_>x||c.lowerStrict&&_>=x||!c.lowerStrict&&_>=x)return"contradiction"}else if(_>x||c.lowerStrict&&_>x)return"contradiction"}}}}}}if(u.length===1&&(a===void 0||!I4(a))){let f=u[0],c=n.lookupDefinition(f);c?ie(c)&&c.value.inferredType&&(n.context?.lexicalScope?.bindings.has(f)?c.value.type=n.type("real"):n.declare(f,{type:"real"})):n.declare(f,{type:"real"})}return s.operator==="Less"||s.operator,n.context.assumptions.set(s,!0),"ok"}function FZ(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(I(i))return N4(n,i.symbol,t);let r=VZ(i);if(r.length===1){let s=Qf(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 I(o,"True")?"tautology":I(o,"False")?"contradiction":"not-a-predicate"}function N4(e,n,t){let i=Qf(t);if(i!=="unknown")return Yl(e,n,i);if(I(t)){let o=AZ[t.symbol];if(o!==void 0)return Yl(e,n,o.type)==="contradiction"||Lp(e,n,o.op,e.number(o.value))==="contradiction"?"contradiction":"ok"}if(m(t,"Range")&&t.ops.length>=2){let o=Yl(e,n,"integer");if(o==="contradiction")return o;let[s,u]=t.ops,a=t.ops[2];return a!==void 0&&a.isSame(-1)&&([s,u]=[u,s]),a!==void 0&&!a.isSame(1)&&!a.isSame(-1)?"ok":Lp(e,n,"GreaterEqual",s)==="contradiction"||Lp(e,n,"LessEqual",u)==="contradiction"?"contradiction":"ok"}if(m(t,"Interval")&&t.ops.length===2){let o=Yl(e,n,"real");if(o==="contradiction")return o;let[s,u]=t.ops,a=!1,l=!1;return m(s,"Open")&&(a=!0,s=s.op1),m(u,"Open")&&(l=!0,u=u.op1),Lp(e,n,a?"Greater":"GreaterEqual",s)==="contradiction"||Lp(e,n,l?"Less":"LessEqual",u)==="contradiction"?"contradiction":"ok"}if(m(t,"SetMinus")&&t.ops.length===2){let[o,s]=t.ops,u=N4(e,n,o.evaluate());if(u==="contradiction"||u==="internal-error")return u;if(m(s,"Set")){for(let l of s.ops)if(p2(e,e.symbol(n),l)==="contradiction")return"contradiction";return"ok"}let a=d2(e,e.symbol(n),s);return a==="tautology"?"ok":a}if(m(t,"Union")&&t.ops.length>0){if(t.ops.every(o=>m(o,"Range"))){if(Yl(e,n,"integer")==="contradiction")return"contradiction"}else if(t.ops.every(o=>m(o,"Interval")||m(o,"Range"))&&Yl(e,n,"real")==="contradiction")return"contradiction"}if(N(t)||B(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 Yl(e,n,t){if(!w4(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=$n({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 Lp(e,n,t,i){return!N(i)||i.isFinite!==!0?"ok":m2(e.function(t,[e.symbol(n),i]))}function LZ(e){let n=r=>{let o=m(r,"Negate")&&r.ops.length===1?r.op1:r,s=Ot(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 I4(e){if(!m(e))return!1;let n=Ot(e);return n!==void 0&&n.part!=="self"?!0:e.ops.some(I4)}function Wo(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 $Z(e,n){let t=Wo(n.lower);if(t!==void 0){let r=n.lowerStrict===!0,o=Wo(e.upper);if(o!==void 0&&(o<t||o===t&&(r||e.upperStrict===!0)))return"contradiction";let s=Wo(e.lower);if(s!==void 0&&(s>t||s===t&&(e.lowerStrict===!0||!r)))return"tautology"}let i=Wo(n.upper);if(i!==void 0){let r=n.upperStrict===!0,o=Wo(e.lower);if(o!==void 0&&(o>i||o===i&&(r||e.lowerStrict===!0)))return"contradiction";let s=Wo(e.upper);if(s!==void 0&&(s<i||s===i&&(e.upperStrict===!0||!r)))return"tautology"}}function BZ(e){let n=Wo(e.lower);if(n!==void 0&&(n>0||n===0&&e.lowerStrict===!0))return!0;let t=Wo(e.upper);return t!==void 0&&(t<0||t===0&&e.upperStrict===!0)}function qZ(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 w4(e,n){return e.lookupDefinition(n)!==void 0}function VZ(e){return e.symbols.filter(n=>!w4(e.engine,n))}function ub(e,n){(e.context.assumptionBindings??=new Set).add(n)}function T4(e,n){let t=e.lookupDefinition(n);return t?!!(ie(t)&&t.value.isConstant||e._getSymbolValue(n)!==void 0):!1}function M4(e,n){if(!Hi(e))return;let t=hd(n),i=mr(e),r=go(t),o=i.bySubject.get(r);if(o!==void 0){let s=bd(o.bounds);if((s==="non-negative"||s==="non-positive")&&o.notEqual.some(u=>u.isSame(0))&&(s=s==="non-negative"?"positive":"negative"),s!==void 0)return s}if(i.inequalitySubjects.has(r))return jZ(e,t)}function jZ(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[u,a]=s;if(a.isSame(0)){if(Zi(u,n)){if(o==="Less")return"negative";if(o==="LessEqual")return"non-positive"}if(m(u,"Negate")&&Zi(u.op1,n)){if(o==="Less")return"positive";if(o==="LessEqual")return"non-negative"}if(m(u,"Subtract")){let[l,f]=u.ops;if(l&&f){if(Zi(f,n)&&l.isNonNegative===!0&&o==="Less")return"positive";if(Zi(l,n)&&f.isNonPositive===!0&&o==="Less")return"negative"}}if(m(u,"Add"))for(let l of u.ops){if(Zi(l,n)){let f=u.ops.filter(c=>c!==l);if(f.length>0&&f.every(c=>c.isNonNegative===!0)){if(o==="Less")return"negative";if(o==="LessEqual")return"non-positive"}}if(m(l,"Negate")&&Zi(l.op1,n)){let f=u.ops.filter(c=>c!==l);if(f.length>0&&f.every(c=>c.isNonNegative===!0)){if(o==="Less")return"positive";if(o==="LessEqual")return"non-negative"}}}}}}function C4(e,n,t){if(typeof n!="string")return e.expr(n,{form:"raw"});let i=ss(n)??n,r=wr(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 g2(e,n){let t=e.expr(n,{form:"raw"}),i=[],r=f=>f.operator.startsWith("_")||We(f)?!0:m(f)?f.ops.some(r):!1,o=f=>{let c=Object.keys(f).sort();for(let p of i){let d=Object.keys(p).sort();if(d.length!==c.length)continue;let g=!0;for(let h=0;h<c.length;h++){if(d[h]!==c[h]){g=!1;break}let b=c[h];if(!f[b].isSame(p[b])){g=!1;break}}if(g)return}i.push(f)},s=e.context.assumptions,u=()=>{let f=new Set;for(let[c,p]of s)if(p===!0)for(let d of c.symbols)f.add(d);return[...f]},a=f=>{let c=f.operator;if(c==="Equal"){if(!m(f)||f.ops.length!==2)return[{pattern:f}];let b=f.op1.canonical.sub(f.op2.canonical);return[{pattern:f},{pattern:e.expr(["Equal",b,0]),matchPermutations:!1}]}if(c!=="Less"&&c!=="LessEqual"&&c!=="Greater"&&c!=="GreaterEqual")return[{pattern:f}];if(!m(f))return[{pattern:f}];let p=c==="Greater"||c==="GreaterEqual"?f.op2:f.op1,d=c==="Greater"||c==="GreaterEqual"?f.op1:f.op2,g=c==="Less"||c==="Greater"?"Less":"LessEqual",h=p.canonical.sub(d.canonical);return[{pattern:f},{pattern:e.expr([g,h,0]),matchPermutations:!1}]};if(m(t,"Element")){let f=t.op1,c=t.op2;if(I(f)&&We(c)){let p=cn(c);if(p&&!p.startsWith("__")){let d=e.expr(f.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 f=cn(t.op2);if(f&&!f.startsWith("__")){let c=t.operator==="Greater"||t.operator==="GreaterEqual",p=t.operator==="Greater"||t.operator==="Less",d=t.op1,g=Ot(d);if(g!==void 0){let h=it(e,g),b=c?h.lower:h.upper,y=c?h.lowerStrict:h.upperStrict;b!==void 0&&(!p||y===!0)&&o({[f]:b})}if(We(d)){let h=cn(d);if(h&&!h.startsWith("__"))for(let b of u()){let y=it(e,b),x=c?y.lower:y.upper,v=c?y.lowerStrict:y.upperStrict;x===void 0||p&&v!==!0||o({[h]:e.expr(b,{form:"canonical"}),[f]:x})}}}}if((t.operator==="Less"||t.operator==="LessEqual")&&m(t)&&We(t.op1)&&!We(t.op2)){let f=cn(t.op1);if(f&&!f.startsWith("__")){let c=t.operator==="Less",p=Ot(t.op2);if(p!==void 0){let d=it(e,p);d.lower!==void 0&&(!c||d.lowerStrict===!0)&&o({[f]:d.lower})}}}let l=a(t);for(let[f,c]of s)if(c===!0)for(let{pattern:p,matchPermutations:d}of l){let g=f.match(p,{useVariations:!0,matchPermutations:d});g!==null&&o(g)}return i.length===0&&!r(t)&&!e._isVerifying&&h2(e,e.expr(n,{form:"canonical"}))===!0&&o({}),i}function h2(e,n){if(!e._isVerifying){e._isVerifying=!0;try{return ab(e,n)}finally{e._isVerifying=!1}}}function ab(e,n){let t=C4(e,n,"verify"),i=t.evaluate();if(I(i)){if(i.symbol==="True")return!0;if(i.symbol==="False")return!1}let r=i.operator;if(r==="Not"&&m(i)){let o=ab(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 u=ab(e,s);if(u===!1)return!1;u===void 0&&(o=!0)}return o?void 0:!0}if(r==="Or"&&m(i)){let o=!1;for(let s of i.ops){let u=ab(e,s);if(u===!0)return!0;u===void 0&&(o=!0)}return o?void 0:!1}if(!A4(t)&&g2(e,t).some(s=>Object.keys(s).length===0))return!0}function A4(e){return e.operator.startsWith("_")||We(e)?!0:m(e)?e.ops.some(A4):!1}function k4(e,n){try{let t=C4(e,n,"assume").canonical;return e._generation+=1,e._mutationGeneration+=1,e.context&&(e.context._assumptionsDirty=!0),c2(t)}catch(t){throw console.error(t instanceof Error?t.message:String(t)),t}}function b2(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)b2(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 R4="https://oeis.org";function zZ(e){return typeof e=="object"&&e!==null?e:null}function JZ(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 GZ(e){return typeof e!="string"?[]:e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n))}function UZ(e){if(!Array.isArray(e))return;let n=e.find(t=>typeof t=="string");return typeof n=="string"?n:void 0}function ZZ(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string");return n.length>0?n:void 0}function HZ(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 YZ(e){if(Array.isArray(e))return e;let n=zZ(e);if(!n)return[];let t=n.results;return Array.isArray(t)?t:[]}function WZ(e){return YZ(e).map(t=>{let i=JZ(t.number),r=i!==void 0?`A${String(i).padStart(6,"0")}`:"";return{id:r,name:typeof t.name=="string"?t.name:"",terms:GZ(t.data),formula:UZ(t.formula),formulas:ZZ(t.formula),comments:HZ(t.comment),url:r?`${R4}/${r}`:""}})}async function lb(e,n={}){let t=n.timeout??1e4,i=n.maxResults??5,r=e.join(","),o=`${R4}/search?fmt=json&q=${encodeURIComponent(r)}&start=0&count=${i}`;try{let s=new AbortController,u=setTimeout(()=>s.abort(),t),a=await fetch(o,{signal:s.signal,headers:{Accept:"application/json"}});if(clearTimeout(u),!a.ok)throw new Error(`OEIS request failed: ${a.status}`);let l=await a.json();return WZ(l).slice(0,i)}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error("OEIS request timed out"):s}}async function P4(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 lb(i,t)}async function D4(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(u=>u.re);return{matches:await lb(o,i),terms:o}}function O4(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=SE(e,n,t);if(!i.valid)throw new Error(i.error);let r=_E(e,n,t),o=e.lookupDefinition(n);return o&&ie(o)&&(o.value.subscriptEvaluate=r),e}function F4(e,n){return tP(e,n)}function L4(e,n){return iP(e,n)}function $4(e){return rP(e)}function B4(e,n){return TE(e,n)}function q4(e,n){oP(e,n)}function V4(e,n){return sP(e,n)}function j4(e,n,t,i,r){return uP(e,n,t,i,r)}function z4(e,n,t){return P4(e,n,t)}function J4(e,n,t,i){return D4(e,n,t,i)}var QZ=4,XZ=[0,1,-1,2,-2,3,4];async function G4(e,n,t){let i=Uc(n)??n,r=bx(n),o=KZ(r);if(!r||!o||o.length<QZ)return{expression:i,candidates:[]};let s;try{s=await lb(o,t)}catch{return{expression:i,candidates:[]}}let u=[],a=new Set;for(let l of s){let f=eH(e,l,r);f&&!a.has(f.id)&&(a.add(f.id),u.push(f))}return{expression:i,candidates:u}}function KZ(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 eH(e,n,t){if(!n.id)return null;for(let i of nH(n))for(let r of tH(i)){let o=iH(e,r);if(o&&oH(o,t))return{expression:o,id:n.id,name:n.name,url:n.url,formula:i.trim()}}return null}function nH(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 tH(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 iH(e,n){let t;try{t=e.parse(rH(n))}catch{return null}return!t||t.operator==="Error"||t.freeVariables.some(i=>i!=="n")?null:t}function rH(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 oH(e,n){for(let t of XZ)if(sH(e,n,t))return!0;return!1}function sH(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 fb=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 fr=class e extends je{_kind="symbol";_hash;_id;_def;constructor(n,t,i){super(n,i?.metadata),An(t),`${t}${yi(t)}`,this._id=t,this._def=i?.def}get json(){return Ri(this._id)?this._id:{sym:this._id}}get hash(){return this._hash??=Pi(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"||I(this.value,"True"):n===!1?this.symbol==="False"||I(this.value,"False"):n instanceof je&&I(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 wu(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 ze&&n.isZero)return this.isNaN||this.isInfinity===!0?this.engine.NaN:this.engine.Zero;if(n instanceof ze){if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return ge(this,this.engine.expr(n))}div(n){return Ja(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||I(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=Su(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"?we(i.value.type.type,n):Xo(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"?we(i.operator.signature.type,n):Xo(i.operator.signature.type,n));return r.matches("never")?!1:r.matches("function")?(i.operator.signature=r,this.engine._mutationGeneration+=1,!0):(xi(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"||cd(n)?fe(this._def)?this._def.operator.signature=n:xi(this.engine,this._id,this._def,{signature:n}):fe(this._def)?xi(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 xl(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:M4(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 vl(this.sgn)}get isNonPositive(){return Sl(this.sgn)}get isNegative(){return _l(this.sgn)}get isNonNegative(){return El(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 pi(n.type)?!1:void 0;if($n({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 pi(n.type)?!1:void 0;if($n({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(Hi(this.engine)&&mr(this.engine).membership.get(this._id)?.notIn.some(i=>I(i,"RealNumbers")))return!1;if(!(n.matches("number")&&!pi(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 Jr(this,n).at(-1)?.value??this}explain(n,t){return yl(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 Vo(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&&J(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 u=t(i,s);if(u!==void 0)return u}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 uH(e,n){return e.lookupDefinition(n)}function U4(e,n){for(let t of Object.keys(n))n[t]=new fr(e,t,{def:uH(e,t)})}function Z4(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 aH=/^-?\d+(\.\d+)?$/;function Gs(e,n,t){let i=t==="+"?0:1,r=null,o=[];for(let s of e)if(aH.test(s)){let u=parseFloat(s);if(t==="*"&&u===0)return"0.0";r===null?r=u:r=t==="+"?r+u:r*u}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 cb(e,n){return m(e,"Add")||m(e,"Subtract")?`(${n})`:n}function H4(e,n){if(I(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=>I(r,"ImaginaryUnit")||N(r)&&r.re===0&&r.im!==0);if(i>=0){let r=t[i],o=I(r,"ImaginaryUnit")?1:r.im,s=t.filter((l,f)=>f!==i);if(s.length===0)return{re:null,im:jn(o)};let u=s.map(l=>cb(l,n(l)));return o!==1&&u.unshift(jn(o)),{re:null,im:Gs(u,"1.0","*")}}}return P.isComplexValued(e)?null:{re:n(e),im:null}}var y2={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 Y4(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")||i6(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,f)=>{if(!(P.isComplexValued(l)||P.isComplexValued(f)))return`Math.abs((${t(l)}) - (${t(f)}))`;let p=h=>{let b=t(h);return P.isComplexValued(h)?{re:`(${b}).re`,im:`(${b}).im`}:{re:`(${b})`,im:"0"}},d=p(l),g=p(f);return`_SYS.cabs({ re: ${d.re} - ${g.re}, im: ${d.im} - ${g.im} })`},u=(l,f)=>`(${s(l,f)} ${o} ${i})`;if(n.length===2)return u(n[0],n[1]);let a=[];for(let l=0;l<n.length-1;l++)a.push(u(n[l],n[l+1]));return`(${a.join(" && ")})`}function so(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}function i6(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 x2(e,n,t){let i=t(e),r=e.type.type;return typeof r!="string"&&r.kind==="tuple"?`${i}[${n}]`:lH(e)?`(${i}).map((_pt) => _pt[${n}])`:`${i}[${n}]`}function lH(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 v2={Equal:(e,n)=>Y4("Equal",e,n),NotEqual:(e,n)=>Y4("NotEqual",e,n),Abs:(e,n)=>P.isComplexValued(e[0])?`_SYS.cabs(${n(e[0])})`:P.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=>P.isComplexValued(s))){let s=e.map(Qe);if(s.every(a=>a!==void 0))return String(s.reduce((a,l)=>a+l,0));let u=e.filter(a=>Qe(a)!==0);return u.length===0?"0":u.length===1?n(u[0]):`(${u.map(a=>n(a)).join(" + ")})`}let i=e.map(s=>({code:n(s),isComplex:P.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)=>P.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 P.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 P.isComplexValued(e)?`_SYS.cacoth(${n(e)})`:`Math.atanh(1 / (${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return P.isComplexValued(e)?`_SYS.cacsc(${n(e)})`:`Math.asin(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return P.isComplexValued(e)?`_SYS.cacsch(${n(e)})`:`Math.asinh(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return P.isComplexValued(e)?`_SYS.casec(${n(e)})`:`Math.acos(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return P.isComplexValued(e)?`_SYS.casech(${n(e)})`:`Math.acosh(1 / (${n(e)}))`},Arcsin:(e,n)=>P.isComplexValued(e[0])?`_SYS.casin(${n(e[0])})`:`Math.asin(${n(e[0])})`,Arsinh:"Math.asinh",Arctan:(e,n)=>P.isComplexValued(e[0])?`_SYS.catan(${n(e[0])})`:`Math.atan(${n(e[0])})`,Artanh:"Math.atanh",Ceil:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`Math.ceil(${n(e[0])})`,Chop:"_SYS.chop",Cos:(e,n)=>P.isComplexValued(e[0])?`_SYS.ccos(${n(e[0])})`:`Math.cos(${n(e[0])})`,Cosh:(e,n)=>P.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 P.isComplexValued(e)?`_SYS.ccot(${n(e)})`:P.inlineExpression("Math.cos(${x}) / Math.sin(${x})",n(e))},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return P.isComplexValued(e)?`_SYS.ccoth(${n(e)})`:P.inlineExpression("(Math.cosh(${x}) / Math.sinh(${x}))",n(e))},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return P.isComplexValued(e)?`_SYS.ccsc(${n(e)})`:`1 / Math.sin(${n(e)})`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return P.isComplexValued(e)?`_SYS.ccsch(${n(e)})`:`1 / Math.sinh(${n(e)})`},Exp:(e,n)=>P.isComplexValued(e[0])?`_SYS.cexp(${n(e[0])})`:`Math.exp(${n(e[0])})`,First:(e,n)=>`${n(e[0])}[0]`,Floor:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`Math.floor(${n(e[0])})`,Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return P.inlineExpression("${x} - Math.floor(${x})",n(e))},Gamma:"_SYS.gamma",GCD:(e,n)=>n6("GCD",e,n),Integrate:(e,n,t)=>xH(e,n,t),LCM:(e,n)=>n6("LCM",e,n),Product:(e,n,t)=>Q4("Product",e,n,t),Sum:(e,n,t)=>Q4("Sum",e,n,t),Limit:(e,n)=>`_SYS.limit(${n(e[0])}, ${n(e[1])})`,Ln:(e,n)=>P.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(!so(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(!so(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(!so(i))throw new Error("Reduce: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=X4(r);if(s===void 0&&(m(r,"Function")||I(r))){if(o==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");s=K4(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 u=n(i);return o!=null?`(${u}).reduce(${s}, ${n(o)})`:`((_l) => _l.length === 0 ? NaN : _l.reduce(${s}))(${u})`},Last:(e,n)=>`_SYS.at(${xe("Last",e[0],n)}, -1)`,Rest:(e,n)=>`(${xe("Rest",e[0],n)}).slice(1)`,Take:(e,n)=>{let t=xe("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=xe("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)=>`(${xe("Reverse",e[0],n)}).slice().reverse()`,Sort:(e,n)=>{let t=xe("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)=>`...(${xe("Join",t,n,i+1)})`).join(", ")}]`,IndexOf:(e,n)=>{let t=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[...(${t}), ${n(e[1])}]`},Most:(e,n)=>`(${xe("Most",e[0],n)}).slice(0, -1)`,Slice:(e,n)=>{let t=xe("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)=>`((${xe("IsEmpty",e[0],n)}).length === 0)`,Count:(e,n)=>`(${xe("Count",e[0],n)}).length`,Contains:(e,n)=>{e[0]&&ea("Contains",e[0]);let t=xe("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]&&ea("Unique",e[0]),`[...new Set(${xe("Unique",e[0],n)})]`),RotateLeft:(e,n)=>{let t=xe("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=xe("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)=>xe("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=xe("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=xe("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")||I(i)&&P.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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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(!so(i))throw new Error("Scan: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=X4(r)??(m(r,"Function")||I(r)?K4(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 u=n(i);return o!=null?`((_f, _l, _a) => _l.map((_x) => (_a = _f(_a, _x))))(${s}, ${u}, ${n(o)})`:`((_f, _l) => { let _a; return _l.map((_x, _i) => (_a = _i === 0 ? _x : _f(_a, _x))); })(${s}, ${u})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");let t=n(e[0]);return P.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 ea("Element",e[1]),`(${xe("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(${xe("Dot",e[0],n,1)}, ${xe("Dot",e[1],n,2)})`},MatrixMultiply:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixMultiply: missing argument");return`_SYS.matmul(${xe("MatrixMultiply",e[0],n,1)}, ${xe("MatrixMultiply",e[1],n,2)})`},Cross:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Cross: missing argument");return`_SYS.cross(${xe("Cross",e[0],n,1)}, ${xe("Cross",e[1],n,2)})`},Norm:(e,n)=>{if(e[0]==null)throw new Error("Norm: missing argument");if(e[1]!=null){if(B(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(${xe("Transpose",e[0],n)})`},Determinant:(e,n)=>`_SYS.det(${xe("Determinant",e[0],n)})`,Inverse:(e,n)=>`_SYS.inv(${xe("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(${xe("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(${xe("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(${xe("Diagonal",e[0],n)})`},MatrixPower:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixPower: missing argument");return`_SYS.matpow(${xe("MatrixPower",e[0],n)}, ${n(e[1])})`},RowReduce:(e,n)=>`_SYS.rref(${xe("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=xe("Flatten",e[0],n);return e[1]!=null?`(${t}).flat(${n(e[1])})`:`(${t}).flat(Infinity)`},Reshape:(e,n)=>{let t=xe("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)=>e6("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)=>e6("Min",e,n),Power:(e,n)=>{let t=e[0],i=e[1];if(t===null)throw new Error("Power: no argument");if(P.isComplexValued(t)||P.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&&(I(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 u=o>=s?1:-1,a=Math.floor(Math.abs(o-s))+1;return a<50?`[${Array.from({length:a},(l,f)=>s+u*f).join(", ")}]`:`Array.from({length: ${a}}, (_e, i) => ${t} ${u===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?P.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&&!P.isIntegerValued(e[0]);if(i!=null&&!r){let u=t?.randomState?t.randomState.counter++:0,a=Oc((i^Math.imul(u+1,2654435761))>>>0)();if(e.length===0)return a.toString();if(e.length===2){let l=n(e[0]),f=n(e[1]);return`((${l}) + Math.floor(${a} * ((${f}) - (${l}))))`}return`Math.floor(${a} * (${n(e[0])}))`}if(e.length===0)return"Math.random()";if(e.length===2){let u=n(e[0]),a=n(e[1]);return`((${u}) + Math.floor(Math.random() * ((${a}) - (${u}))))`}let o=e[0];return P.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 P.isIntegerValued(e[0])?n(e[0]):P.inlineExpression("(Math.sign(${x}) * Math.round(Math.abs(${x})))",n(e[0]));let t=P.tempVar(),i=P.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(I(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 P.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 P.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)=>P.isComplexValued(e[0])?`_SYS.csin(${n(e[0])})`:`Math.sin(${n(e[0])})`,Sinh:(e,n)=>P.isComplexValued(e[0])?`_SYS.csinh(${n(e[0])})`:`Math.sinh(${n(e[0])})`,Sqrt:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_SYS.ctan(${n(e[0])})`:`Math.tan(${n(e[0])})`,Tanh:(e,n)=>P.isComplexValued(e[0])?`_SYS.ctanh(${n(e[0])})`:`Math.tanh(${n(e[0])})`,Third:(e,n)=>`${n(e[0])}[2]`,PointX:(e,n)=>x2(e[0],0,n),PointY:(e,n)=>x2(e[0],1,n),PointZ:(e,n)=>x2(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 P.isIntegerValued(e)&&P.isIntegerValued(n)&&P.isNonNegative(e)?`(${i} % ${r})`:`(((${i} % ${r}) + ${r}) % ${r})`},Truncate:(e,n)=>P.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=P.isComplexValued(e),r=P.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(!P.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=>P.isComplexValued(s))){if(e.some(a=>Qe(a)===0))return"0";let s=e.map(Qe);if(s.every(a=>a!==void 0))return String(s.reduce((a,l)=>a*l,1));let u=e.filter(a=>Qe(a)!==1);return u.length===0?"1":u.length===1?n(u[0]):`(${u.map(a=>n(a)).join(" * ")})`}if(e.length===2){let s=P.isComplexValued(e[0]),u=P.isComplexValued(e[1]),a=n(e[0]),l=n(e[1]);return s&&u?`(() => { const _a = ${a}, _b = ${l}; return { re: _a.re * _b.re - _a.im * _b.im, im: _a.re * _b.im + _a.im * _b.re }; })()`:s&&!u?`(() => { const _a = ${a}, _r = ${l}; return { re: _a.re * _r, im: _a.im * _r }; })()`:`(() => { const _r = ${a}, _b = ${l}; return { re: _r * _b.re, im: _r * _b.im }; })()`}let i=[],r=[];for(let s=0;s<e.length;s++){let u=`_v${s}`;r.push(u),i.push(`const ${u} = ${n(e[s])}`)}let o=P.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 u=r[s],a=P.isComplexValued(e[s]),l=a?`${u}.re`:u,f=a?`${u}.im`:"0";i.push(`const _nre${s} = _re * ${l} - _im * ${f}`),i.push(`const _nim${s} = _re * ${f} + _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 P.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)=>P.isComplexValued(e[0])?`(${n(e[0])}).re`:n(e[0]),Imaginary:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).im`:"0",Argument:(e,n)=>P.isComplexValued(e[0])?`_SYS.carg(${n(e[0])})`:`(${n(e[0])} >= 0 ? 0 : Math.PI)`,Conjugate:(e,n)=>P.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 cr(e){if(e!==void 0&&Number.isFinite(e)&&!(Math.abs(e-1)<1e-9))return e}function oo(e){if(typeof e=="string"){let t=Rt(e),i={r:t>>>24&255,g:t>>>16&255,b:t>>>8&255},r=cr((t&255)/255);return r!==void 0&&(i.alpha=r),i}let n=Os({L:e[0],C:e[1],H:e[2]});if(e.length>=4){let t=cr(e[3]);t!==void 0&&(n.alpha=t)}return n}function $p(e){if(typeof e=="string"){let n=Rt(e),t=n>>>24&255,i=n>>>16&255,r=n>>>8&255,o=Pn({r:t,g:i,b:r}),s=cr((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?cr(e[3]):void 0}}function pb(e){let n=e>>>24&255,t=e>>>16&255,i=e>>>8&255,r=Pn({r:n,g:t,b:i}),o=cr((e&255)/255);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]}var fH={color(e){return pb(Rt(e))},colorToString(e,n){let t=oo(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))),u=`#${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;if(t.alpha!==void 0){let a=Math.round(Math.max(0,Math.min(255,t.alpha*255)));u+=a.toString(16).padStart(2,"0")}return u}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=Ps(t.r,t.g,t.b),o=Math.round(r.h*10)/10,s=Math.round(r.s*1e3)/10,u=Math.round(r.l*1e3)/10;return t.alpha!==void 0?`hsl(${o} ${s}% ${u}% / ${t.alpha})`:`hsl(${o} ${s}% ${u}%)`}case"oklch":{let r=Pn(t),o=Math.round(r.L*1e3)/1e3,s=Math.round(r.C*1e3)/1e3,u=Math.round(r.H*10)/10;return t.alpha!==void 0?`oklch(${o} ${s} ${u} / ${t.alpha})`:`oklch(${o} ${s} ${u})`}default:throw new Error(`Unknown color format: ${i}`)}},colorMix(e,n,t=.5){let i=$p(e),r=$p(n);t=Math.max(0,Math.min(1,t));let o=i.C<1e-6,s=r.C<1e-6,u;if(o&&s)u=i.H;else if(o)u=r.H;else if(s)u=i.H;else{let d=r.H-i.H;d>180&&(d-=360),d<-180&&(d+=360),u=i.H+d*t,u<0&&(u+=360),u>=360&&(u-=360)}let a=i.L+(r.L-i.L)*t,l=i.C+(r.C-i.C)*t,f=i.alpha??1,c=r.alpha??1,p=cr(f+(c-f)*t);return p!==void 0?[a,l,u,p]:[a,l,u]},colorContrast(e,n){return Pl(oo(e),oo(n))},contrastingColor(e,n,t){let i=oo(e);return pb(n!==void 0&&t!==void 0?Fl({bg:i,fg1:oo(n),fg2:oo(t)}):Fl(i))},colorToColorspace(e,n){let t=oo(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=Ps(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=Ol(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={...Ih,...Sh,...Nh}[e];if(!i)throw new Error(`Unknown palette: ${e}`);let r=i.map(s=>pb(Rt(s)));if(n===void 0)return r;if(Number.isInteger(n)&&n>=2){let s=n,u=[];for(let a=0;a<s;a++){let l=s===1?0:a/(s-1);u.push(this._interpolatePalette(r,l))}return u}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,u]=e[i],[a,l,f]=e[i+1],c=s<1e-6,p=l<1e-6,d;if(c&&p)d=u;else if(c)d=f;else if(p)d=u;else{let g=f-u;g>180&&(g-=360),g<-180&&(g+=360),d=u+g*r,d<0&&(d+=360),d>=360&&(d-=360)}return[o+(a-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 u=Rs(t,i,r);s=Pn(u);break}case"oklch":s={L:t,C:i,H:r};break;case"oklab":case"lab":s=Ds({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=cr(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=cr(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=Rs(e,n,t),o=Pn({r:r.r,g:r.g,b:r.b}),s=cr(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=Ds({L:e,a:n,b:t}),o=cr(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=cr(i);return r!==void 0?[e,n,t,r]:[e,n,t]},asRgb(e){let n=oo(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=oo(e),t=Eh(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=oo(e),t=Ps(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=$p(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($p(e)),i=zi($p(n));return _h(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 db(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]=db(e,...n.map(o=>Array.isArray(o)?o[r]:o));return i}function I2(e,n){let t=Array.isArray(e?.[0]),i=Array.isArray(n?.[0]);if(!t&&!i){if(e.length!==n.length)return NaN;let a=0;for(let l=0;l<e.length;l++)a+=e[l]*n[l];return a}if(t&&!i)return e.map(a=>a.length===n.length?a.reduce((l,f,c)=>l+f*n[c],0):NaN);if(!t&&i){if(e.length!==n.length)return NaN;let a=n[0].length,l=new Array(a).fill(0);for(let f=0;f<e.length;f++)for(let c=0;c<a;c++)l[c]+=e[f]*n[f][c];return l}let r=e.length,o=e[0].length;if(n.length!==o)return NaN;let s=n[0].length,u=[];for(let a=0;a<r;a++){let l=new Array(s).fill(0);for(let f=0;f<o;f++){let c=e[a][f];for(let p=0;p<s;p++)l[p]+=c*n[f][p]}u.push(l)}return u}function cH(...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]),u=!Array.isArray(o[0]);if(s&&u){if(i.length!==o.length)return NaN;let a=new Array(i.length);for(let l=0;l<i.length;l++)a[l]=i[l]*o[l];i=a}else{let a=I2(i,o);if(typeof a=="number")return a;i=a}}return t!==1&&(i=db(r=>r*t,i)),i}function Wl(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);if(i&&r){if(e.length!==n.length)return!1;for(let a=0;a<e.length;a++)if(Wl(e[a],n[a],t)!==!0)return!1;return!0}if(i)return e.map(a=>Wl(a,n,t));if(r)return n.map(a=>Wl(e,a,t));let o=a=>typeof a=="object"&&a!==null&&"re"in a?a:{re:a,im:0},s=o(e),u=o(n);return Math.hypot(s.re-u.re,s.im-u.im)<=t}function _2(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);return i&&r?Wl(e,n,t)!==!0:i?e.map(o=>_2(o,n,t)):r?n.map(o=>_2(e,o,t)):Wl(e,n,t)!==!0}function r6(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 u=t[s][i];if(u!==0)for(let a=0;a<2*n;a++)t[s][a]-=u*t[i][a]}}return t.map(i=>i.slice(n))}function pH(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 dH(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 mH(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=r6(e);if(!Array.isArray(s))return NaN;i=s,r=-r}let o=Array.from({length:t},(s,u)=>Array.from({length:t},(a,l)=>u===l?1:0));for(let s=0;s<r;s++)o=I2(o,i);return o}function gH(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 a=r+1;a<n;a++)Math.abs(i[a][o])>Math.abs(i[s][o])&&(s=a);if(i[s][o]===0)continue;s!==r&&([i[s],i[r]]=[i[r],i[s]]);let u=i[r][o];for(let a=0;a<t;a++)i[r][a]/=u;for(let a=0;a<n;a++){if(a===r)continue;let l=i[a][o];if(l!==0)for(let f=0;f<t;f++)i[a][f]-=l*i[r][f]}r++}return i}var o6={bcast:db,add:(e,n)=>db((t,i)=>t+i,e,n),chop:df,factorial:pf,factorial2:tu,gamma:Me,gcd:cf,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:Oc(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:I2,mul:cH,eq:Wl,neq:_2,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 u=0;for(let a=0;a<r.length;a++)u+=Math.abs(r[a][s]);o=Math.max(o,u)}return o}if(n===1/0){let o=0;for(let s of r){let u=0;for(let a of s)u+=Math.abs(a);o=Math.max(o,u)}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 u=t[s][r]/t[r][r];for(let a=r;a<n;a++)t[s][a]-=u*t[r][a]}}return i},inv:r6,conjTranspose:pH,diagonal:dH,matpow:mH,rref:gH,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,u)=>i(o*n[1]+u))):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=Fu(e,n,t);return i.converged?i.estimate:Nl(e,n,t,1e7).estimate},integrateMC:(e,n,t)=>Nl(e,n,t,1e7).estimate,lcm:md,lngamma:Sn,limit:mo,mean:Vh,median:Uu,variance:Bl,populationVariance:ql,standardDeviation:qP,populationStandardDeviation:VP,kurtosis:jh,skewness:zh,mode:Jh,quartiles:Cp,interquartileRange:Hh,covariance:Gh,populationCovariance:Uh,correlation:Zh,erf:Do,erfc:Po,erfInv:el,beta:wm,gammaQ:Xa,betaRegularized:Ka,digamma:nl,trigamma:tl,polygamma:Im,zeta:Dr,lambertW:Tm,besselJ:Pr,besselY:Wa,besselI:ko,besselK:Mm,airyAi:Rm,airyBi:Pm,airyAiPrime:Dm,airyBiPrime:Om,sinc:Fm,fresnelS:Or,fresnelC:Fr,sinIntegral:qm,cosIntegral:Vm,expIntegralEi:Ro,logIntegral:jm,erfi:$m,agm:Ec,ellipticK:_c,ellipticE:Sc,ellipticEIncomplete:wc,ellipticF:Ic,ellipticPiComplete:Tc,ellipticPiIncomplete:Mc,hypergeometric2F1:Cc,hypergeometric1F1:Ac,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 u=0;u<s;u++){let a=t*t-i*i+r;i=2*t*i+o,t=a;let l=t*t+i*i;if(l>4){let f=(u-Math.log2(Math.log2(l))+4)/s;return Math.max(0,Math.min(1,f))}}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,u=Math.round(t);for(let a=0;a<u;a++){let l=i*i-r*r+o;r=2*i*r+s,i=l;let f=i*i+r*r;if(f>4){let c=(a-Math.log2(Math.log2(f))+4)/u;return Math.max(0,Math.min(1,c))}}return 1},binomial:Ga,fibonacci:N2,csin:e=>dn(new F(e.re,e.im).sin()),ccos:e=>dn(new F(e.re,e.im).cos()),ctan:e=>dn(new F(e.re,e.im).tan()),casin:e=>dn(new F(e.re,e.im).asin()),cacos:e=>dn(new F(e.re,e.im).acos()),catan:e=>dn(new F(e.re,e.im).atan()),csinh:e=>dn(new F(e.re,e.im).sinh()),ccosh:e=>dn(new F(e.re,e.im).cosh()),ctanh:e=>dn(new F(e.re,e.im).tanh()),csqrt:e=>dn(new F(e.re,e.im).sqrt()),cexp:e=>dn(new F(e.re,e.im).exp()),cln:e=>dn(new F(e.re,e.im).log()),cpow:(e,n)=>{let t=typeof e=="number"?new F(e,0):new F(e.re,e.im),i=typeof n=="number"?new F(n,0):new F(n.re,n.im);return dn(t.pow(i))},ccot:e=>dn(new F(e.re,e.im).cot()),csec:e=>dn(new F(e.re,e.im).sec()),ccsc:e=>dn(new F(e.re,e.im).csc()),ccoth:e=>dn(new F(e.re,e.im).coth()),csech:e=>dn(new F(e.re,e.im).sech()),ccsch:e=>dn(new F(e.re,e.im).csch()),cacot:e=>dn(new F(e.re,e.im).acot()),casec:e=>dn(new F(e.re,e.im).asec()),cacsc:e=>dn(new F(e.re,e.im).acsc()),cacoth:e=>dn(new F(e.re,e.im).acoth()),casech:e=>dn(new F(e.re,e.im).asech()),cacsch:e=>dn(new F(e.re,e.im).acsch()),cabs:e=>new F(e.re,e.im).abs(),carg:e=>new F(e.re,e.im).arg(),cconj:e=>dn(new F(e.re,e.im).conjugate()),cneg:e=>({re:-e.re,im:-e.im}),...fH},S2=class extends Function{SYS=o6;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)})}},mb=class extends Function{SYS=o6;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)})}},Bp=class{getOperators(){return y2}getFunctions(){return v2}createTarget(n={}){return{language:"javascript",operators:t=>y2[t],functions:t=>v2[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}`),P.buildInterpreterFallback(n,r,"javascript",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=ro(n);let{operators:i,functions:r,vars:o,imports:s=[],preamble:u,realOnly:a,iterationBudget:l,quadrature:f}=t,c=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 fr=class e extends je{_kind="symbol";_hash;_id;_def;constructor(n,t,i){super(n,i?.metadata),An(t),`${t}${yi(t)}`,this._id=t,this._def=i?.def}get json(){return Ri(this._id)?this._id:{sym:this._id}}get hash(){return this._hash??=Pi(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"||I(this.value,"True"):n===!1?this.symbol==="False"||I(this.value,"False"):n instanceof je&&I(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 wu(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 ze&&n.isZero)return this.isNaN||this.isInfinity===!0?this.engine.NaN:this.engine.Zero;if(n instanceof ze){if(n.isOne)return this;if(n.isNegativeOne)return this.neg()}return ge(this,this.engine.expr(n))}div(n){return Ja(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||I(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=Su(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"?we(i.value.type.type,n):Xo(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"?we(i.operator.signature.type,n):Xo(i.operator.signature.type,n));return r.matches("never")?!1:r.matches("function")?(i.operator.signature=r,this.engine._mutationGeneration+=1,!0):(xi(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"||cd(n)?fe(this._def)?this._def.operator.signature=n:xi(this.engine,this._id,this._def,{signature:n}):fe(this._def)?xi(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 xl(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:M4(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 vl(this.sgn)}get isNonPositive(){return Sl(this.sgn)}get isNegative(){return _l(this.sgn)}get isNonNegative(){return El(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 pi(n.type)?!1:void 0;if($n({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 pi(n.type)?!1:void 0;if($n({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(Hi(this.engine)&&mr(this.engine).membership.get(this._id)?.notIn.some(i=>I(i,"RealNumbers")))return!1;if(!(n.matches("number")&&!pi(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 Jr(this,n).at(-1)?.value??this}explain(n,t){return yl(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 Vo(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&&J(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 u=t(i,s);if(u!==void 0)return u}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 uH(e,n){return e.lookupDefinition(n)}function U4(e,n){for(let t of Object.keys(n))n[t]=new fr(e,t,{def:uH(e,t)})}function Z4(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 aH=/^-?\d+(\.\d+)?$/;function Gs(e,n,t){let i=t==="+"?0:1,r=null,o=[];for(let s of e)if(aH.test(s)){let u=parseFloat(s);if(t==="*"&&u===0)return"0.0";r===null?r=u:r=t==="+"?r+u:r*u}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 cb(e,n){return m(e,"Add")||m(e,"Subtract")?`(${n})`:n}function H4(e,n){if(I(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=>I(r,"ImaginaryUnit")||N(r)&&r.re===0&&r.im!==0);if(i>=0){let r=t[i],o=I(r,"ImaginaryUnit")?1:r.im,s=t.filter((l,f)=>f!==i);if(s.length===0)return{re:null,im:jn(o)};let u=s.map(l=>cb(l,n(l)));return o!==1&&u.unshift(jn(o)),{re:null,im:Gs(u,"1.0","*")}}}return P.isComplexValued(e)?null:{re:n(e),im:null}}var y2={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 Y4(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")||i6(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,f)=>{if(!(P.isComplexValued(l)||P.isComplexValued(f)))return`Math.abs((${t(l)}) - (${t(f)}))`;let p=h=>{let b=t(h);return P.isComplexValued(h)?{re:`(${b}).re`,im:`(${b}).im`}:{re:`(${b})`,im:"0"}},d=p(l),g=p(f);return`_SYS.cabs({ re: ${d.re} - ${g.re}, im: ${d.im} - ${g.im} })`},u=(l,f)=>`(${s(l,f)} ${o} ${i})`;if(n.length===2)return u(n[0],n[1]);let a=[];for(let l=0;l<n.length-1;l++)a.push(u(n[l],n[l+1]));return`(${a.join(" && ")})`}function so(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}function i6(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 x2(e,n,t){let i=t(e),r=e.type.type;return typeof r!="string"&&r.kind==="tuple"?`${i}[${n}]`:lH(e)?`(${i}).map((_pt) => _pt[${n}])`:`${i}[${n}]`}function lH(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 v2={Equal:(e,n)=>Y4("Equal",e,n),NotEqual:(e,n)=>Y4("NotEqual",e,n),Abs:(e,n)=>P.isComplexValued(e[0])?`_SYS.cabs(${n(e[0])})`:P.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(a=>P.isComplexValued(a))){let a=e.map(Qe);if(a.every(f=>f!==void 0))return String(a.reduce((f,c)=>f+c,0));let l=e.filter(f=>Qe(f)!==0);return l.length===0?"0":l.length===1?n(l[0]):`(${l.map(f=>n(f)).join(" + ")})`}let i=[],r=e.map(a=>{let l=n(a),f=P.isComplexValued(a);if(f&&!I(a)&&!N(a)){let c=P.tempVar();return i.push([c,l]),{code:c,isComplex:f,bound:!0}}return{code:l,isComplex:f,bound:!1}}),o=r.map(a=>a.isComplex?a.bound?`${a.code}.re`:`(${a.code}).re`:a.code),s=r.filter(a=>a.isComplex).map(a=>a.bound?`${a.code}.im`:`(${a.code}).im`),u=`({ re: ${o.join(" + ")}, im: ${s.join(" + ")} })`;return i.length===0?u:`(() => { const ${i.map(([a,l])=>`${a} = ${l}`).join(", ")}; return ${u}; })()`},Arccos:(e,n)=>P.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 P.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 P.isComplexValued(e)?`_SYS.cacoth(${n(e)})`:`Math.atanh(1 / (${n(e)}))`},Arccsc:([e],n)=>{if(e===null)throw new Error("Arccsc: no argument");return P.isComplexValued(e)?`_SYS.cacsc(${n(e)})`:`Math.asin(1 / (${n(e)}))`},Arcsch:([e],n)=>{if(e===null)throw new Error("Arcsch: no argument");return P.isComplexValued(e)?`_SYS.cacsch(${n(e)})`:`Math.asinh(1 / (${n(e)}))`},Arcsec:([e],n)=>{if(e===null)throw new Error("Arcsec: no argument");return P.isComplexValued(e)?`_SYS.casec(${n(e)})`:`Math.acos(1 / (${n(e)}))`},Arsech:([e],n)=>{if(e===null)throw new Error("Arsech: no argument");return P.isComplexValued(e)?`_SYS.casech(${n(e)})`:`Math.acosh(1 / (${n(e)}))`},Arcsin:(e,n)=>P.isComplexValued(e[0])?`_SYS.casin(${n(e[0])})`:`Math.asin(${n(e[0])})`,Arsinh:"Math.asinh",Arctan:(e,n)=>P.isComplexValued(e[0])?`_SYS.catan(${n(e[0])})`:`Math.atan(${n(e[0])})`,Artanh:"Math.atanh",Ceil:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`Math.ceil(${n(e[0])})`,Chop:"_SYS.chop",Cos:(e,n)=>P.isComplexValued(e[0])?`_SYS.ccos(${n(e[0])})`:`Math.cos(${n(e[0])})`,Cosh:(e,n)=>P.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 P.isComplexValued(e)?`_SYS.ccot(${n(e)})`:P.inlineExpression("Math.cos(${x}) / Math.sin(${x})",n(e))},Coth:([e],n)=>{if(e===null)throw new Error("Coth: no argument");return P.isComplexValued(e)?`_SYS.ccoth(${n(e)})`:P.inlineExpression("(Math.cosh(${x}) / Math.sinh(${x}))",n(e))},Csc:([e],n)=>{if(e===null)throw new Error("Csc: no argument");return P.isComplexValued(e)?`_SYS.ccsc(${n(e)})`:`1 / Math.sin(${n(e)})`},Csch:([e],n)=>{if(e===null)throw new Error("Csch: no argument");return P.isComplexValued(e)?`_SYS.ccsch(${n(e)})`:`1 / Math.sinh(${n(e)})`},Exp:(e,n)=>P.isComplexValued(e[0])?`_SYS.cexp(${n(e[0])})`:`Math.exp(${n(e[0])})`,First:(e,n)=>`${n(e[0])}[0]`,Floor:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`Math.floor(${n(e[0])})`,Fract:([e],n)=>{if(e===null)throw new Error("Fract: no argument");return P.inlineExpression("${x} - Math.floor(${x})",n(e))},Gamma:"_SYS.gamma",GCD:(e,n)=>n6("GCD",e,n),Integrate:(e,n,t)=>xH(e,n,t),LCM:(e,n)=>n6("LCM",e,n),Product:(e,n,t)=>Q4("Product",e,n,t),Sum:(e,n,t)=>Q4("Sum",e,n,t),Limit:(e,n)=>`_SYS.limit(${n(e[0])}, ${n(e[1])})`,Ln:(e,n)=>P.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(!so(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(!so(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(!so(i))throw new Error("Reduce: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=X4(r);if(s===void 0&&(m(r,"Function")||I(r))){if(o==null)throw new Error("Reduce: a custom combiner compiles only with an explicit initial value. Fail closed (D6).");s=K4(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 u=n(i);return o!=null?`(${u}).reduce(${s}, ${n(o)})`:`((_l) => _l.length === 0 ? NaN : _l.reduce(${s}))(${u})`},Last:(e,n)=>`_SYS.at(${xe("Last",e[0],n)}, -1)`,Rest:(e,n)=>`(${xe("Rest",e[0],n)}).slice(1)`,Take:(e,n)=>{let t=xe("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=xe("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)=>`(${xe("Reverse",e[0],n)}).slice().reverse()`,Sort:(e,n)=>{let t=xe("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)=>`...(${xe("Join",t,n,i+1)})`).join(", ")}]`,IndexOf:(e,n)=>{let t=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[...(${t}), ${n(e[1])}]`},Most:(e,n)=>`(${xe("Most",e[0],n)}).slice(0, -1)`,Slice:(e,n)=>{let t=xe("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)=>`((${xe("IsEmpty",e[0],n)}).length === 0)`,Count:(e,n)=>`(${xe("Count",e[0],n)}).length`,Contains:(e,n)=>{e[0]&&ea("Contains",e[0]);let t=xe("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]&&ea("Unique",e[0]),`[...new Set(${xe("Unique",e[0],n)})]`),RotateLeft:(e,n)=>{let t=xe("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=xe("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)=>xe("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=xe("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=xe("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")||I(i)&&P.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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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=xe("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(!so(i))throw new Error("Scan: cannot compile \u2014 first operand is not an indexed collection (list/vector/range). Fail closed (D6).");let s=X4(r)??(m(r,"Function")||I(r)?K4(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 u=n(i);return o!=null?`((_f, _l, _a) => _l.map((_x) => (_a = _f(_a, _x))))(${s}, ${u}, ${n(o)})`:`((_f, _l) => { let _a; return _l.map((_x, _i) => (_a = _i === 0 ? _x : _f(_a, _x))); })(${s}, ${u})`},Boole:(e,n)=>{if(e[0]==null)throw new Error("Boole: missing argument");let t=n(e[0]);return P.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 ea("Element",e[1]),`(${xe("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(${xe("Dot",e[0],n,1)}, ${xe("Dot",e[1],n,2)})`},MatrixMultiply:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixMultiply: missing argument");return`_SYS.matmul(${xe("MatrixMultiply",e[0],n,1)}, ${xe("MatrixMultiply",e[1],n,2)})`},Cross:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("Cross: missing argument");return`_SYS.cross(${xe("Cross",e[0],n,1)}, ${xe("Cross",e[1],n,2)})`},Norm:(e,n)=>{if(e[0]==null)throw new Error("Norm: missing argument");if(e[1]!=null){if(B(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(${xe("Transpose",e[0],n)})`},Determinant:(e,n)=>`_SYS.det(${xe("Determinant",e[0],n)})`,Inverse:(e,n)=>`_SYS.inv(${xe("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(${xe("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(${xe("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(${xe("Diagonal",e[0],n)})`},MatrixPower:(e,n)=>{if(e[0]==null||e[1]==null)throw new Error("MatrixPower: missing argument");return`_SYS.matpow(${xe("MatrixPower",e[0],n)}, ${n(e[1])})`},RowReduce:(e,n)=>`_SYS.rref(${xe("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=xe("Flatten",e[0],n);return e[1]!=null?`(${t}).flat(${n(e[1])})`:`(${t}).flat(Infinity)`},Reshape:(e,n)=>{let t=xe("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)=>e6("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)=>e6("Min",e,n),Power:(e,n)=>{let t=e[0],i=e[1];if(t===null)throw new Error("Power: no argument");if(P.isComplexValued(t)||P.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&&(I(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 u=o>=s?1:-1,a=Math.floor(Math.abs(o-s))+1;return a<50?`[${Array.from({length:a},(l,f)=>s+u*f).join(", ")}]`:`Array.from({length: ${a}}, (_e, i) => ${t} ${u===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?P.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&&!P.isIntegerValued(e[0]);if(i!=null&&!r){let u=t?.randomState?t.randomState.counter++:0,a=Oc((i^Math.imul(u+1,2654435761))>>>0)();if(e.length===0)return a.toString();if(e.length===2){let l=n(e[0]),f=n(e[1]);return`((${l}) + Math.floor(${a} * ((${f}) - (${l}))))`}return`Math.floor(${a} * (${n(e[0])}))`}if(e.length===0)return"Math.random()";if(e.length===2){let u=n(e[0]),a=n(e[1]);return`((${u}) + Math.floor(Math.random() * ((${a}) - (${u}))))`}let o=e[0];return P.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 P.isIntegerValued(e[0])?n(e[0]):P.inlineExpression("(Math.sign(${x}) * Math.round(Math.abs(${x})))",n(e[0]));let t=P.tempVar(),i=P.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(I(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 P.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 P.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)=>P.isComplexValued(e[0])?`_SYS.csin(${n(e[0])})`:`Math.sin(${n(e[0])})`,Sinh:(e,n)=>P.isComplexValued(e[0])?`_SYS.csinh(${n(e[0])})`:`Math.sinh(${n(e[0])})`,Sqrt:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_SYS.ctan(${n(e[0])})`:`Math.tan(${n(e[0])})`,Tanh:(e,n)=>P.isComplexValued(e[0])?`_SYS.ctanh(${n(e[0])})`:`Math.tanh(${n(e[0])})`,Third:(e,n)=>`${n(e[0])}[2]`,PointX:(e,n)=>x2(e[0],0,n),PointY:(e,n)=>x2(e[0],1,n),PointZ:(e,n)=>x2(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 P.isIntegerValued(e)&&P.isIntegerValued(n)&&P.isNonNegative(e)?`(${i} % ${r})`:`(((${i} % ${r}) + ${r}) % ${r})`},Truncate:(e,n)=>P.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=P.isComplexValued(e),r=P.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(!P.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=>P.isComplexValued(s))){if(e.some(a=>Qe(a)===0))return"0";let s=e.map(Qe);if(s.every(a=>a!==void 0))return String(s.reduce((a,l)=>a*l,1));let u=e.filter(a=>Qe(a)!==1);return u.length===0?"1":u.length===1?n(u[0]):`(${u.map(a=>n(a)).join(" * ")})`}if(e.length===2){let s=P.isComplexValued(e[0]),u=P.isComplexValued(e[1]),a=n(e[0]),l=n(e[1]);return s&&u?`(() => { const _a = ${a}, _b = ${l}; return { re: _a.re * _b.re - _a.im * _b.im, im: _a.re * _b.im + _a.im * _b.re }; })()`:s&&!u?`(() => { const _a = ${a}, _r = ${l}; return { re: _a.re * _r, im: _a.im * _r }; })()`:`(() => { const _r = ${a}, _b = ${l}; return { re: _r * _b.re, im: _r * _b.im }; })()`}let i=[],r=[];for(let s=0;s<e.length;s++){let u=`_v${s}`;r.push(u),i.push(`const ${u} = ${n(e[s])}`)}let o=P.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 u=r[s],a=P.isComplexValued(e[s]),l=a?`${u}.re`:u,f=a?`${u}.im`:"0";i.push(`const _nre${s} = _re * ${l} - _im * ${f}`),i.push(`const _nim${s} = _re * ${f} + _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 P.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)=>P.isComplexValued(e[0])?`(${n(e[0])}).re`:n(e[0]),Imaginary:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).im`:"0",Argument:(e,n)=>P.isComplexValued(e[0])?`_SYS.carg(${n(e[0])})`:`(${n(e[0])} >= 0 ? 0 : Math.PI)`,Conjugate:(e,n)=>P.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 cr(e){if(e!==void 0&&Number.isFinite(e)&&!(Math.abs(e-1)<1e-9))return e}function oo(e){if(typeof e=="string"){let t=Rt(e),i={r:t>>>24&255,g:t>>>16&255,b:t>>>8&255},r=cr((t&255)/255);return r!==void 0&&(i.alpha=r),i}let n=Os({L:e[0],C:e[1],H:e[2]});if(e.length>=4){let t=cr(e[3]);t!==void 0&&(n.alpha=t)}return n}function $p(e){if(typeof e=="string"){let n=Rt(e),t=n>>>24&255,i=n>>>16&255,r=n>>>8&255,o=Pn({r:t,g:i,b:r}),s=cr((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?cr(e[3]):void 0}}function pb(e){let n=e>>>24&255,t=e>>>16&255,i=e>>>8&255,r=Pn({r:n,g:t,b:i}),o=cr((e&255)/255);return o!==void 0?[r.L,r.C,r.H,o]:[r.L,r.C,r.H]}var fH={color(e){return pb(Rt(e))},colorToString(e,n){let t=oo(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))),u=`#${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;if(t.alpha!==void 0){let a=Math.round(Math.max(0,Math.min(255,t.alpha*255)));u+=a.toString(16).padStart(2,"0")}return u}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=Ps(t.r,t.g,t.b),o=Math.round(r.h*10)/10,s=Math.round(r.s*1e3)/10,u=Math.round(r.l*1e3)/10;return t.alpha!==void 0?`hsl(${o} ${s}% ${u}% / ${t.alpha})`:`hsl(${o} ${s}% ${u}%)`}case"oklch":{let r=Pn(t),o=Math.round(r.L*1e3)/1e3,s=Math.round(r.C*1e3)/1e3,u=Math.round(r.H*10)/10;return t.alpha!==void 0?`oklch(${o} ${s} ${u} / ${t.alpha})`:`oklch(${o} ${s} ${u})`}default:throw new Error(`Unknown color format: ${i}`)}},colorMix(e,n,t=.5){let i=$p(e),r=$p(n);t=Math.max(0,Math.min(1,t));let o=i.C<1e-6,s=r.C<1e-6,u;if(o&&s)u=i.H;else if(o)u=r.H;else if(s)u=i.H;else{let d=r.H-i.H;d>180&&(d-=360),d<-180&&(d+=360),u=i.H+d*t,u<0&&(u+=360),u>=360&&(u-=360)}let a=i.L+(r.L-i.L)*t,l=i.C+(r.C-i.C)*t,f=i.alpha??1,c=r.alpha??1,p=cr(f+(c-f)*t);return p!==void 0?[a,l,u,p]:[a,l,u]},colorContrast(e,n){return Pl(oo(e),oo(n))},contrastingColor(e,n,t){let i=oo(e);return pb(n!==void 0&&t!==void 0?Fl({bg:i,fg1:oo(n),fg2:oo(t)}):Fl(i))},colorToColorspace(e,n){let t=oo(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=Ps(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=Ol(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={...Ih,...Sh,...Nh}[e];if(!i)throw new Error(`Unknown palette: ${e}`);let r=i.map(s=>pb(Rt(s)));if(n===void 0)return r;if(Number.isInteger(n)&&n>=2){let s=n,u=[];for(let a=0;a<s;a++){let l=s===1?0:a/(s-1);u.push(this._interpolatePalette(r,l))}return u}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,u]=e[i],[a,l,f]=e[i+1],c=s<1e-6,p=l<1e-6,d;if(c&&p)d=u;else if(c)d=f;else if(p)d=u;else{let g=f-u;g>180&&(g-=360),g<-180&&(g+=360),d=u+g*r,d<0&&(d+=360),d>=360&&(d-=360)}return[o+(a-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 u=Rs(t,i,r);s=Pn(u);break}case"oklch":s={L:t,C:i,H:r};break;case"oklab":case"lab":s=Ds({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=cr(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=cr(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=Rs(e,n,t),o=Pn({r:r.r,g:r.g,b:r.b}),s=cr(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=Ds({L:e,a:n,b:t}),o=cr(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=cr(i);return r!==void 0?[e,n,t,r]:[e,n,t]},asRgb(e){let n=oo(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=oo(e),t=Eh(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=oo(e),t=Ps(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=$p(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($p(e)),i=zi($p(n));return _h(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 db(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]=db(e,...n.map(o=>Array.isArray(o)?o[r]:o));return i}function I2(e,n){let t=Array.isArray(e?.[0]),i=Array.isArray(n?.[0]);if(!t&&!i){if(e.length!==n.length)return NaN;let a=0;for(let l=0;l<e.length;l++)a+=e[l]*n[l];return a}if(t&&!i)return e.map(a=>a.length===n.length?a.reduce((l,f,c)=>l+f*n[c],0):NaN);if(!t&&i){if(e.length!==n.length)return NaN;let a=n[0].length,l=new Array(a).fill(0);for(let f=0;f<e.length;f++)for(let c=0;c<a;c++)l[c]+=e[f]*n[f][c];return l}let r=e.length,o=e[0].length;if(n.length!==o)return NaN;let s=n[0].length,u=[];for(let a=0;a<r;a++){let l=new Array(s).fill(0);for(let f=0;f<o;f++){let c=e[a][f];for(let p=0;p<s;p++)l[p]+=c*n[f][p]}u.push(l)}return u}function cH(...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]),u=!Array.isArray(o[0]);if(s&&u){if(i.length!==o.length)return NaN;let a=new Array(i.length);for(let l=0;l<i.length;l++)a[l]=i[l]*o[l];i=a}else{let a=I2(i,o);if(typeof a=="number")return a;i=a}}return t!==1&&(i=db(r=>r*t,i)),i}function Wl(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);if(i&&r){if(e.length!==n.length)return!1;for(let a=0;a<e.length;a++)if(Wl(e[a],n[a],t)!==!0)return!1;return!0}if(i)return e.map(a=>Wl(a,n,t));if(r)return n.map(a=>Wl(e,a,t));let o=a=>typeof a=="object"&&a!==null&&"re"in a?a:{re:a,im:0},s=o(e),u=o(n);return Math.hypot(s.re-u.re,s.im-u.im)<=t}function _2(e,n,t){let i=Array.isArray(e),r=Array.isArray(n);return i&&r?Wl(e,n,t)!==!0:i?e.map(o=>_2(o,n,t)):r?n.map(o=>_2(e,o,t)):Wl(e,n,t)!==!0}function r6(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 u=t[s][i];if(u!==0)for(let a=0;a<2*n;a++)t[s][a]-=u*t[i][a]}}return t.map(i=>i.slice(n))}function pH(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 dH(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 mH(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=r6(e);if(!Array.isArray(s))return NaN;i=s,r=-r}let o=Array.from({length:t},(s,u)=>Array.from({length:t},(a,l)=>u===l?1:0));for(let s=0;s<r;s++)o=I2(o,i);return o}function gH(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 a=r+1;a<n;a++)Math.abs(i[a][o])>Math.abs(i[s][o])&&(s=a);if(i[s][o]===0)continue;s!==r&&([i[s],i[r]]=[i[r],i[s]]);let u=i[r][o];for(let a=0;a<t;a++)i[r][a]/=u;for(let a=0;a<n;a++){if(a===r)continue;let l=i[a][o];if(l!==0)for(let f=0;f<t;f++)i[a][f]-=l*i[r][f]}r++}return i}var o6={bcast:db,add:(e,n)=>db((t,i)=>t+i,e,n),chop:df,factorial:pf,factorial2:tu,gamma:Me,gcd:cf,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:Oc(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:I2,mul:cH,eq:Wl,neq:_2,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 u=0;for(let a=0;a<r.length;a++)u+=Math.abs(r[a][s]);o=Math.max(o,u)}return o}if(n===1/0){let o=0;for(let s of r){let u=0;for(let a of s)u+=Math.abs(a);o=Math.max(o,u)}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 u=t[s][r]/t[r][r];for(let a=r;a<n;a++)t[s][a]-=u*t[r][a]}}return i},inv:r6,conjTranspose:pH,diagonal:dH,matpow:mH,rref:gH,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,u)=>i(o*n[1]+u))):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=Fu(e,n,t);return i.converged?i.estimate:Nl(e,n,t,1e7).estimate},integrateMC:(e,n,t)=>Nl(e,n,t,1e7).estimate,lcm:md,lngamma:Sn,limit:mo,mean:Vh,median:Uu,variance:Bl,populationVariance:ql,standardDeviation:qP,populationStandardDeviation:VP,kurtosis:jh,skewness:zh,mode:Jh,quartiles:Cp,interquartileRange:Hh,covariance:Gh,populationCovariance:Uh,correlation:Zh,erf:Do,erfc:Po,erfInv:el,beta:wm,gammaQ:Xa,betaRegularized:Ka,digamma:nl,trigamma:tl,polygamma:Im,zeta:Dr,lambertW:Tm,besselJ:Pr,besselY:Wa,besselI:ko,besselK:Mm,airyAi:Rm,airyBi:Pm,airyAiPrime:Dm,airyBiPrime:Om,sinc:Fm,fresnelS:Or,fresnelC:Fr,sinIntegral:qm,cosIntegral:Vm,expIntegralEi:Ro,logIntegral:jm,erfi:$m,agm:Ec,ellipticK:_c,ellipticE:Sc,ellipticEIncomplete:wc,ellipticF:Ic,ellipticPiComplete:Tc,ellipticPiIncomplete:Mc,hypergeometric2F1:Cc,hypergeometric1F1:Ac,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 u=0;u<s;u++){let a=t*t-i*i+r;i=2*t*i+o,t=a;let l=t*t+i*i;if(l>4){let f=(u-Math.log2(Math.log2(l))+4)/s;return Math.max(0,Math.min(1,f))}}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,u=Math.round(t);for(let a=0;a<u;a++){let l=i*i-r*r+o;r=2*i*r+s,i=l;let f=i*i+r*r;if(f>4){let c=(a-Math.log2(Math.log2(f))+4)/u;return Math.max(0,Math.min(1,c))}}return 1},binomial:Ga,fibonacci:N2,csin:e=>dn(new F(e.re,e.im).sin()),ccos:e=>dn(new F(e.re,e.im).cos()),ctan:e=>dn(new F(e.re,e.im).tan()),casin:e=>dn(new F(e.re,e.im).asin()),cacos:e=>dn(new F(e.re,e.im).acos()),catan:e=>dn(new F(e.re,e.im).atan()),csinh:e=>dn(new F(e.re,e.im).sinh()),ccosh:e=>dn(new F(e.re,e.im).cosh()),ctanh:e=>dn(new F(e.re,e.im).tanh()),csqrt:e=>dn(new F(e.re,e.im).sqrt()),cexp:e=>dn(new F(e.re,e.im).exp()),cln:e=>dn(new F(e.re,e.im).log()),cpow:(e,n)=>{let t=typeof e=="number"?new F(e,0):new F(e.re,e.im),i=typeof n=="number"?new F(n,0):new F(n.re,n.im);return dn(t.pow(i))},ccot:e=>dn(new F(e.re,e.im).cot()),csec:e=>dn(new F(e.re,e.im).sec()),ccsc:e=>dn(new F(e.re,e.im).csc()),ccoth:e=>dn(new F(e.re,e.im).coth()),csech:e=>dn(new F(e.re,e.im).sech()),ccsch:e=>dn(new F(e.re,e.im).csch()),cacot:e=>dn(new F(e.re,e.im).acot()),casec:e=>dn(new F(e.re,e.im).asec()),cacsc:e=>dn(new F(e.re,e.im).acsc()),cacoth:e=>dn(new F(e.re,e.im).acoth()),casech:e=>dn(new F(e.re,e.im).asech()),cacsch:e=>dn(new F(e.re,e.im).acsch()),cabs:e=>new F(e.re,e.im).abs(),carg:e=>new F(e.re,e.im).arg(),cconj:e=>dn(new F(e.re,e.im).conjugate()),cneg:e=>({re:-e.re,im:-e.im}),...fH},S2=class extends Function{SYS=o6;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)})}},mb=class extends Function{SYS=o6;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)})}},Bp=class{getOperators(){return y2}getFunctions(){return v2}createTarget(n={}){return{language:"javascript",operators:t=>y2[t],functions:t=>v2[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}`),P.buildInterpreterFallback(n,r,"javascript",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=ro(n);let{operators:i,functions:r,vars:o,imports:s=[],preamble:u,realOnly:a,iterationBudget:l,quadrature:f}=t,c=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"?vH(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 y2[y]},h=this.createTarget({operators:g,functions:y=>d?.[y]?d[y]:v2[y],var:y=>{if(o&&y in o){let v=o[y];return typeof v=="string"?v:JSON.stringify(v)}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(c.includes(y))return`_.${y}`;if(n.engine._getSymbolValue(y)===void 0)return`_.${y}`},preamble:(u??"")+p,iterationBudget:l,quadrature:f,varsKeys:o?new Set(Object.keys(o)):void 0,randomSeed:n.engine._randomNumericSeed(),randomState:{counter:0},userFunctions:{defs:new Map,compiling:new Set}}),b=hH(n,h,a);return P.withReferences(b,n,h,o?new Set(Object.keys(o)):void 0)}};function E2(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 hH(e,n,t){if(m(e,"Function")){let a=e.ops,l=a.slice(1).map(g=>fn(g)||"_"),f=P.compile(a[0].canonical,{...n,var:g=>l.includes(g)?g:n.var(g),boundVars:P.withBoundNames(n,l)}),c=P.userFunctionsPreamble(n),p=new mb(f,l,c),d={target:"javascript",success:!0,code:c?`(${l.join(", ")}) => { ${c}return ${f}; }`:`(${l.join(", ")}) => ${f}`,calling:"lambda",run:p};return t?E2(d):d}if(I(e)){let a=n.operators?.(e.symbol);if(a){let l=new mb(`a ${a[0]} b`,["a","b"]),f={target:"javascript",success:!0,code:`(a, b) => a ${a[0]} b`,calling:"lambda",run:l};return t?E2(f):f}}let i=P.compile(e,n),r=P.userFunctionsPreamble(n),o=r?n.preamble?`${n.preamble}
|
|
144
|
-
${r}`:r:n.preamble,s=new S2(i,o),u={target:"javascript",success:!0,code:i,calling:"expression",run:s};return t?E2(u):u}var bH=100;function s6(e){e.operator;let n=e,t=I(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 W4(e,n,t){return n!==void 0?String(n):`Math.floor(${P.compile(e,t)})`}function Q4(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1]){if(so(n[0]))return t6(e,n[0],i,!1);if(i6(n[0]))return t6(e,n[0],i,!0);throw new Error(`${e}: no indexing set`)}return u6(e,n[0],n.slice(1),i)}function xe(e,n,t,i){if(!n||!so(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 X4(e){if(I(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 K4(e,n,t){let i=!1;if(m(e,"Function"))i=e.nops-1===2;else if(I(e)){let r=P.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 ea(e,n){let t=De(n.type.type);if(!(t!==void 0&&(t==="number"||$(t,"real")||$(t,"boolean")||$(t,"string"))&&!P.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 e6(e,n,t){let i=e==="Max"?"Math.max":"Math.min",r=e==="Max"?"-Infinity":"Infinity";return n.length===1&&n[0]&&so(n[0])?`(${t(n[0])}).reduce((_a, _b) => ${i}(_a, _b), ${r})`:n.some(o=>o&&so(o))?`[${n.map(s=>so(s)?`...(${t(s)})`:t(s)).join(", ")}].reduce((_a, _b) => ${i}(_a, _b), ${r})`:`${i}(${n.map(o=>t(o)).join(", ")})`}function n6(e,n,t){let i=e==="GCD"?"_SYS.gcd":"_SYS.lcm",r=e==="GCD"?"0":"1",o=n.map(s=>{if(so(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 t6(e,n,t,i){let r=P.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 u6(e,n,t,i){P.assertScalarBigOpBody(e,n);let{index:r,lowerExpr:o,upperExpr:s,lowerNum:u,upperNum:a}=s6(t[0]),l=t.slice(1),f=e==="Sum",c=f?"+":"*",p=f?"0":"1",d=P.isComplexValued(n),g=w=>l.length>0?u6(e,n,l,w):P.compile(n,w),h=u!==void 0&&a!==void 0;if(h&&u>a)return p;if(h&&a-u+1<=bH){let M=[];for(let O=u;O<=a;O++){let j={...i,var:G=>G===r?String(O):i.var(G),boundVars:P.withBoundNames(i,[r])};M.push(`(${g(j)})`)}if(!d)return`(${M.join(` ${c} `)})`;let A=M.map((O,j)=>`_t${j}`),k=M.map((O,j)=>`const ${A[j]} = ${O}`).join("; ");if(f){let O=A.map(G=>`${G}.re`).join(" + "),j=A.map(G=>`${G}.im`).join(" + ");return`(() => { ${k}; return { re: ${O}, im: ${j} }; })()`}let D=A[0],q=[k];for(let O=1;O<A.length;O++){let j=D;D=`_p${O}`,q.push(`const ${D} = { re: ${j}.re * ${A[O]}.re - ${j}.im * ${A[O]}.im, im: ${j}.re * ${A[O]}.im + ${j}.im * ${A[O]}.re }`)}return`(() => { ${q.join("; ")}; return ${D}; })()`}let b=W4(o,u,i),y=W4(s,a,i),x=g({...i,var:w=>w===r?r:i.var(w),boundVars:P.withBoundNames(i,[r])}),v=P.tempVar(),S=i.iterationBudget,_=w=>S!==void 0?`if (!(_upper - ${r} < ${S})) return ${w}; `:"";if(d){let w=P.tempVar(),M=_("{ re: NaN, im: NaN }");return f?`(() => { let ${v} = { re: 0, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${M}while (${r} <= _upper) { const ${w} = ${x}; ${v} = { re: ${v}.re + ${w}.re, im: ${v}.im + ${w}.im }; ${r}++; } return ${v}; })()`:`(() => { let ${v} = { re: 1, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${M}while (${r} <= _upper) { const ${w} = ${x}; ${v} = { re: ${v}.re * ${w}.re - ${v}.im * ${w}.im, im: ${v}.re * ${w}.im + ${v}.im * ${w}.re }; ${r}++; } return ${v}; })()`}return`(() => { let ${v} = ${p}; let ${r} = ${b}; const _upper = ${y}; ${_("NaN")}while (${r} <= _upper) { ${v} ${c}= ${x}; ${r}++; } return ${v}; })()`}function yH(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 xH(e,n,t){if(!yH(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}=s6(e[1]),s=i,u=e[0];if(m(e[0],"Function")){let p=fn(e[0].ops[1]);p&&(s=p),u=e[0].ops[0]}let a=P.compile(u,{...t,var:p=>p===s?p:t.var(p),boundVars:P.withBoundNames(t,[s])}),l=P.compile(r,t),f=P.compile(o,t);return`${t.quadrature==="monte-carlo"?"_SYS.integrateMC":"_SYS.integrate"}((${s}) => (${a}), ${l}, ${f})`}function vH(e){let n=e.toString();return n.includes("=>")?!1:n.startsWith("function ")&&n.includes(e.name)}function N2(e){if(!Number.isInteger(e))return NaN;if(e<0)return e%2===0?-N2(-e):N2(-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 a6={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]},EH=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"]),_H=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 SH(e){return e==="wgsl"?_H:e==="glsl"?EH:new Set}function k2(e,n){if(SH(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 Ji(e){return e?.language==="wgsl"?"vec2f":"vec2"}function Ql(e){return e?.language==="wgsl"?"vec3f":"vec3"}function A2(e){return e?.language==="wgsl"?"bitcast<f32>(0x7fc00000u)":"_gpu_nan()"}function c6(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(P.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 w2(e,n){let t=c6(e);return t===void 0?A2(n):`${n?.language==="wgsl"?`vec${t}f`:`vec${t}`}(${A2(n)})`}function qp(e,n,t,i){return i?.language==="wgsl"?`select(${t}, ${n}, ${e})`:`((${e}) ? (${n}) : (${t}))`}function gb(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 T2(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 M2(e){return B(e)?e.string?.toLowerCase()??null:null}function l6(e,n,t){let i=Qe(e);return i!==void 0&&Number.isInteger(i)?i.toString():`${t?.language==="wgsl"?"i32":"int"}(${n(e)})`}var NH=100,IH=4;function f6(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(P.assertScalarBigOpBody(e,n[0]),P.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=I(o[0])?o[0].symbol:"_",u=o[1].re,a=o[2].re,l=!isNaN(u)&&Number.isFinite(u)?Math.floor(u):void 0,f=!isNaN(a)&&Number.isFinite(a)?Math.floor(a):void 0,c=e==="Sum",p=c?"+":"*",d=c?"0.0":"1.0",g=i.language==="wgsl",h=l!==void 0&&f!==void 0;if(h&&l>f)return d;if(h&&f-l+1<=NH){let D=[];for(let q=l;q<=f;q++){let O=Us(q),j={...i,var:G=>G===s?O:i.var(G)};D.push(`(${P.compile(n[0],j)})`)}return`(${D.join(` ${p} `)})`}let b=P.tempVar(),y=g?"f32":"float",x=g?"i32":"int",v={...i,var:D=>D===s?g?`f32(${s})`:`float(${s})`:i.var(D)},S=P.compile(n[0],v),_=l!==void 0?String(l):P.compile(o[1],i),w=f!==void 0?String(f):P.compile(o[2],i);k2(s,i.language);let M=g?`var ${b}: ${y}`:`${y} ${b}`,A=g?`var ${s}: ${x}`:`${x} ${s}`;return[`${M} = ${d};`,`for (${A} = ${_}; ${s} <= ${w}; ${s}++) {`,` ${b} ${p}= ${S};`,"}",`return ${b};`].join(`
|
|
145
|
-
`)}var wH={Add:(e,n,t)=>{if(e.length===0)return"0.0";if(e.length===1)return n(e[0]);if(!e.some(l=>P.isComplexValued(l)))return Gs(e.map(l=>n(l)),"0.0","+");let r=e.map(l=>H4(l,n));if(r.some(l=>l===null)){let l=Ji(t);return e.map(f=>{let c=n(f);return P.isComplexValued(f)?c:`${l}(${c}, 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 u=Gs(o,"0.0","+"),a=Gs(s,"0.0","+");return`${Ji(t)}(${u}, ${a})`},Multiply:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);if(!e.some(l=>P.isComplexValued(l)))return Gs(e.map(l=>n(l)),"1.0","*");let r=e.findIndex(l=>I(l,"ImaginaryUnit")||N(l)&&l.re===0&&l.im!==0);if(r>=0){let l=e[r],f=I(l,"ImaginaryUnit")?1:l.im,c=e.filter((h,b)=>b!==r),p=Ji(t);if(c.length===0)return`${p}(0.0, ${jn(f)})`;let d=c.map(h=>cb(h,n(h)));f!==1&&d.unshift(jn(f));let g=Gs(d,"1.0","*");return`${p}(0.0, ${g})`}let o=[],s=[];for(let l of e)P.isComplexValued(l)?s.push(n(l)):o.push(cb(l,n(l)));let u=Gs(o,"1.0","*"),a=s[0];for(let l=1;l<s.length;l++)a=`_gpu_cmul(${a}, ${s[l]})`;return u!=="1.0"&&(a=`(${u} * ${a})`),a},Divide:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);let i=P.isComplexValued(e[0]),r=e.length>=2&&P.isComplexValued(e[1]);if(!i&&!r){if(e.length===2){let u=Qe(e[0]),a=Qe(e[1]);return u!==void 0&&a!==void 0&&a!==0?jn(u/a):a===1?n(e[0]):`${n(e[0])} / ${n(e[1])}`}let s=n(e[0]);for(let u=1;u<e.length;u++)s=`${s} / ${n(e[u])}`;return s}return i&&r?`_gpu_cdiv(${n(e[0])}, ${n(e[1])})`:i&&!r?`(${n(e[0])} / ${n(e[1])})`:`_gpu_cdiv(${Ji(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?`${Ji(t)}(${jn(-e.re)}, ${jn(-e.im)})`:I(e,"ImaginaryUnit")?`${Ji(t)}(0.0, -1.0)`:`(-${n(e)})`},Abs:(e,n)=>P.isComplexValued(e[0])?`length(${n(e[0])})`:P.isNonNegative(e[0])?n(e[0]):`abs(${n(e[0])})`,Arccos:(e,n)=>P.isComplexValued(e[0])?`_gpu_cacos(${n(e[0])})`:`acos(${n(e[0])})`,Arcsin:(e,n)=>P.isComplexValued(e[0])?`_gpu_casin(${n(e[0])})`:`asin(${n(e[0])})`,Arctan:(e,n)=>P.isComplexValued(e[0])?`_gpu_catan(${n(e[0])})`:`atan(${n(e[0])})`,Ceil:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`ceil(${n(e[0])})`,Clamp:"clamp",Cos:(e,n)=>P.isComplexValued(e[0])?`_gpu_ccos(${n(e[0])})`:`cos(${n(e[0])})`,Degrees:"radians",Exp:(e,n)=>P.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)=>T2(e[0],"x",n),PointY:(e,n)=>T2(e[0],"y",n),PointZ:(e,n)=>T2(e[0],"z",n),Floor:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`floor(${n(e[0])})`,Fract:"fract",Ln:(e,n)=>P.isComplexValued(e[0])?`_gpu_cln(${n(e[0])})`:`log(${n(e[0])})`,Log2:"log2",Max:(e,n)=>gb("max",e,n),Min:(e,n)=>gb("min",e,n),ElementMax:(e,n)=>gb("max",e,n),ElementMin:(e,n)=>gb("min",e,n),Mix:"mix",If:(e,n,t)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return qp(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 I(e[1],"True")?`(${n(e[0])})`:I(e[1],"False")?w2(e[0],t):qp(n(e[1]),n(e[0]),w2(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=>c6(o))??null,r=o=>{if(o>=e.length)return w2(i,t);let s=e[o],u=e[o+1];return I(s,"True")?`(${n(u)})`:qp(n(s),n(u),r(o+2),t)};return r(0)},Match:(e,n,t)=>P.compileMatchTernary(e[0].engine,e,t,{ternary:(i,r,o)=>qp(i,r,o,t),eq:"==",noMatch:A2(t),allowStrings:!1}),Power:(e,n,t)=>{let i=e[0],r=e[1];if(i===null)throw new Error("Power: no argument");if(P.isComplexValued(i)||P.isComplexValued(r)){if(I(i,"ExponentialE"))return`_gpu_cexp(${n(r)})`;let u=Ji(t),a=P.isComplexValued(i)?n(i):`${u}(${n(i)}, 0.0)`,l=P.isComplexValued(r)?n(r):`${u}(${n(r)}, 0.0)`;return`_gpu_cpow(${a}, ${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 u=s,a=Math.abs(u),l;if(a===1)l=`(${n(i)})`;else if((I(i)||N(i))&&a<=IH){let f=n(i);l=`(${Array(a).fill(f).join(" * ")})`}else l=`_gpu_powi(${n(i)}, ${Us(a)})`;return u<0?`(1.0 / ${l})`:l}return`pow(${n(i)}, ${n(r)})`},Radians:"radians",Round:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_gpu_csin(${n(e[0])})`:`sin(${n(e[0])})`,Smoothstep:"smoothstep",Sqrt:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_gpu_ctan(${n(e[0])})`:`tan(${n(e[0])})`,Truncate:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`trunc(${n(e[0])})`,Real:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).x`:n(e[0]),Imaginary:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).y`:"0.0",Argument:(e,n,t)=>{if(P.isComplexValued(e[0])){let i=n(e[0]);return`atan(${i}.y, ${i}.x)`}return qp(`${n(e[0])} >= 0.0`,"0.0","3.14159265359",t)},Conjugate:(e,n,t)=>{if(P.isComplexValued(e[0])){let i=Ji(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(P.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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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)=>P.isComplexValued(e[0])?`_gpu_csinh(${n(e[0])})`:`sinh(${n(e[0])})`,Cosh:(e,n)=>P.isComplexValued(e[0])?`_gpu_ccosh(${n(e[0])})`:`cosh(${n(e[0])})`,Tanh:(e,n)=>P.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(P.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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(t)}(1.0, 0.0), _gpu_ccosh(${n(e)}))`:`(1.0 / cosh(${n(e)}))`},Arcosh:(e,n)=>P.isComplexValued(e[0])?`_gpu_cacosh(${n(e[0])})`:`acosh(${n(e[0])})`,Arsinh:(e,n)=>P.isComplexValued(e[0])?`_gpu_casinh(${n(e[0])})`:`asinh(${n(e[0])})`,Artanh:(e,n)=>P.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(I(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 a=n(e[1]),l=n(e[2]);return`(abs(_gpu_apca(${i}, ${a})) >= abs(_gpu_apca(${i}, ${l})) ? ${a} : ${l})`}let o=t?.language==="wgsl"?"vec3f":"vec3",s=`${o}(0.0)`,u=`${o}(1.0, 0.0, 0.0)`;return`((_gpu_apca(${i}, ${s}) > 50.0) ? ${s} : ${u})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");let i=M2(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=M2(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=M2(e);if(i===null)throw new Error("Color: argument must be a string literal on GPU target");let r=Rt(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,u=r>>>8&255,a=Pn({r:o,g:s,b:u});return`${Ql(t)}(${jn(a.L)}, ${jn(a.C)}, ${jn(a.H)})`},Rgb:(e,n,t)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_gpu_srgb_to_oklch(${Ql(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(${Ql(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(${Ql(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(${Ql(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`${Ql(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=l6(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=l6(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)=>f6("Sum",e,n,t),Product:(e,n,t)=>f6("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 u=[];for(let f=0;f<s;f++)u.push(i+f*o);return`${t.language==="wgsl"?`array<f32, ${s}>`:`float[${s}]`}(${u.map(Us).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(!I(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;k2(s,t.language);let u=Math.floor(o.ops[0].re),a=Math.floor(o.ops[1].re);if(!Number.isFinite(u)||!Number.isFinite(a))throw new Error("Loop: bounds must be finite numbers");let l=t.language==="wgsl",f=l?"i32":"int",c=l?`f32(${s})`:`float(${s})`,p=P.compile(e[0],{...t,var:g=>g===s?c:t.var(g)});return`for (${l?`var ${s}: ${f}`:`${f} ${s}`} = ${u}; ${s} <= ${a}; ${s}++) {
|
|
144
|
+
${r}`:r:n.preamble,s=new S2(i,o),u={target:"javascript",success:!0,code:i,calling:"expression",run:s};return t?E2(u):u}var bH=100;function s6(e){e.operator;let n=e,t=I(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 W4(e,n,t){return n!==void 0?String(n):`Math.floor(${P.compile(e,t)})`}function Q4(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1]){if(so(n[0]))return t6(e,n[0],i,!1);if(i6(n[0]))return t6(e,n[0],i,!0);throw new Error(`${e}: no indexing set`)}return u6(e,n[0],n.slice(1),i)}function xe(e,n,t,i){if(!n||!so(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 X4(e){if(I(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 K4(e,n,t){let i=!1;if(m(e,"Function"))i=e.nops-1===2;else if(I(e)){let r=P.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 ea(e,n){let t=De(n.type.type);if(!(t!==void 0&&(t==="number"||$(t,"real")||$(t,"boolean")||$(t,"string"))&&!P.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 e6(e,n,t){let i=e==="Max"?"Math.max":"Math.min",r=e==="Max"?"-Infinity":"Infinity";return n.length===1&&n[0]&&so(n[0])?`(${t(n[0])}).reduce((_a, _b) => ${i}(_a, _b), ${r})`:n.some(o=>o&&so(o))?`[${n.map(s=>so(s)?`...(${t(s)})`:t(s)).join(", ")}].reduce((_a, _b) => ${i}(_a, _b), ${r})`:`${i}(${n.map(o=>t(o)).join(", ")})`}function n6(e,n,t){let i=e==="GCD"?"_SYS.gcd":"_SYS.lcm",r=e==="GCD"?"0":"1",o=n.map(s=>{if(so(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 t6(e,n,t,i){let r=P.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 u6(e,n,t,i){P.assertScalarBigOpBody(e,n);let{index:r,lowerExpr:o,upperExpr:s,lowerNum:u,upperNum:a}=s6(t[0]),l=t.slice(1),f=e==="Sum",c=f?"+":"*",p=f?"0":"1",d=P.isComplexValued(n),g=w=>l.length>0?u6(e,n,l,w):P.compile(n,w),h=u!==void 0&&a!==void 0;if(h&&u>a)return p;if(h&&a-u+1<=bH){let M=[];for(let O=u;O<=a;O++){let j={...i,var:G=>G===r?String(O):i.var(G),boundVars:P.withBoundNames(i,[r])};M.push(`(${g(j)})`)}if(!d)return`(${M.join(` ${c} `)})`;let A=M.map((O,j)=>`_t${j}`),k=M.map((O,j)=>`const ${A[j]} = ${O}`).join("; ");if(f){let O=A.map(G=>`${G}.re`).join(" + "),j=A.map(G=>`${G}.im`).join(" + ");return`(() => { ${k}; return { re: ${O}, im: ${j} }; })()`}let D=A[0],q=[k];for(let O=1;O<A.length;O++){let j=D;D=`_p${O}`,q.push(`const ${D} = { re: ${j}.re * ${A[O]}.re - ${j}.im * ${A[O]}.im, im: ${j}.re * ${A[O]}.im + ${j}.im * ${A[O]}.re }`)}return`(() => { ${q.join("; ")}; return ${D}; })()`}let b=W4(o,u,i),y=W4(s,a,i),x=g({...i,var:w=>w===r?r:i.var(w),boundVars:P.withBoundNames(i,[r])}),v=P.tempVar(),S=i.iterationBudget,_=w=>S!==void 0?`if (!(_upper - ${r} < ${S})) return ${w}; `:"";if(d){let w=P.tempVar(),M=_("{ re: NaN, im: NaN }");return f?`(() => { let ${v} = { re: 0, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${M}while (${r} <= _upper) { const ${w} = ${x}; ${v} = { re: ${v}.re + ${w}.re, im: ${v}.im + ${w}.im }; ${r}++; } return ${v}; })()`:`(() => { let ${v} = { re: 1, im: 0 }; let ${r} = ${b}; const _upper = ${y}; ${M}while (${r} <= _upper) { const ${w} = ${x}; ${v} = { re: ${v}.re * ${w}.re - ${v}.im * ${w}.im, im: ${v}.re * ${w}.im + ${v}.im * ${w}.re }; ${r}++; } return ${v}; })()`}return`(() => { let ${v} = ${p}; let ${r} = ${b}; const _upper = ${y}; ${_("NaN")}while (${r} <= _upper) { ${v} ${c}= ${x}; ${r}++; } return ${v}; })()`}function yH(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 xH(e,n,t){if(!yH(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}=s6(e[1]),s=i,u=e[0];if(m(e[0],"Function")){let p=fn(e[0].ops[1]);p&&(s=p),u=e[0].ops[0]}let a=P.compile(u,{...t,var:p=>p===s?p:t.var(p),boundVars:P.withBoundNames(t,[s])}),l=P.compile(r,t),f=P.compile(o,t);return`${t.quadrature==="monte-carlo"?"_SYS.integrateMC":"_SYS.integrate"}((${s}) => (${a}), ${l}, ${f})`}function vH(e){let n=e.toString();return n.includes("=>")?!1:n.startsWith("function ")&&n.includes(e.name)}function N2(e){if(!Number.isInteger(e))return NaN;if(e<0)return e%2===0?-N2(-e):N2(-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 a6={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]},EH=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"]),_H=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 SH(e){return e==="wgsl"?_H:e==="glsl"?EH:new Set}function k2(e,n){if(SH(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 Ji(e){return e?.language==="wgsl"?"vec2f":"vec2"}function Ql(e){return e?.language==="wgsl"?"vec3f":"vec3"}function A2(e){return e?.language==="wgsl"?"bitcast<f32>(0x7fc00000u)":"_gpu_nan()"}function c6(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(P.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 w2(e,n){let t=c6(e);return t===void 0?A2(n):`${n?.language==="wgsl"?`vec${t}f`:`vec${t}`}(${A2(n)})`}function qp(e,n,t,i){return i?.language==="wgsl"?`select(${t}, ${n}, ${e})`:`((${e}) ? (${n}) : (${t}))`}function gb(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 T2(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 M2(e){return B(e)?e.string?.toLowerCase()??null:null}function l6(e,n,t){let i=Qe(e);return i!==void 0&&Number.isInteger(i)?i.toString():`${t?.language==="wgsl"?"i32":"int"}(${n(e)})`}var NH=100,IH=4;function f6(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(P.assertScalarBigOpBody(e,n[0]),P.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=I(o[0])?o[0].symbol:"_",u=o[1].re,a=o[2].re,l=!isNaN(u)&&Number.isFinite(u)?Math.floor(u):void 0,f=!isNaN(a)&&Number.isFinite(a)?Math.floor(a):void 0,c=e==="Sum",p=c?"+":"*",d=c?"0.0":"1.0",g=i.language==="wgsl",h=l!==void 0&&f!==void 0;if(h&&l>f)return d;if(h&&f-l+1<=NH){let D=[];for(let q=l;q<=f;q++){let O=Us(q),j={...i,var:G=>G===s?O:i.var(G),boundVars:P.withBoundNames(i,[s])};D.push(`(${P.compile(n[0],j)})`)}return`(${D.join(` ${p} `)})`}let b=P.tempVar(),y=g?"f32":"float",x=g?"i32":"int",v={...i,var:D=>D===s?g?`f32(${s})`:`float(${s})`:i.var(D),boundVars:P.withBoundNames(i,[s])},S=P.compile(n[0],v),_=l!==void 0?String(l):P.compile(o[1],i),w=f!==void 0?String(f):P.compile(o[2],i);k2(s,i.language);let M=g?`var ${b}: ${y}`:`${y} ${b}`,A=g?`var ${s}: ${x}`:`${x} ${s}`;return[`${M} = ${d};`,`for (${A} = ${_}; ${s} <= ${w}; ${s}++) {`,` ${b} ${p}= ${S};`,"}",`return ${b};`].join(`
|
|
145
|
+
`)}var wH={Add:(e,n,t)=>{if(e.length===0)return"0.0";if(e.length===1)return n(e[0]);if(!e.some(l=>P.isComplexValued(l)))return Gs(e.map(l=>n(l)),"0.0","+");let r=e.map(l=>H4(l,n));if(r.some(l=>l===null)){let l=Ji(t);return e.map(f=>{let c=n(f);return P.isComplexValued(f)?c:`${l}(${c}, 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 u=Gs(o,"0.0","+"),a=Gs(s,"0.0","+");return`${Ji(t)}(${u}, ${a})`},Multiply:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);if(!e.some(l=>P.isComplexValued(l)))return Gs(e.map(l=>n(l)),"1.0","*");let r=e.findIndex(l=>I(l,"ImaginaryUnit")||N(l)&&l.re===0&&l.im!==0);if(r>=0){let l=e[r],f=I(l,"ImaginaryUnit")?1:l.im,c=e.filter((h,b)=>b!==r),p=Ji(t);if(c.length===0)return`${p}(0.0, ${jn(f)})`;let d=c.map(h=>cb(h,n(h)));f!==1&&d.unshift(jn(f));let g=Gs(d,"1.0","*");return`${p}(0.0, ${g})`}let o=[],s=[];for(let l of e)P.isComplexValued(l)?s.push(n(l)):o.push(cb(l,n(l)));let u=Gs(o,"1.0","*"),a=s[0];for(let l=1;l<s.length;l++)a=`_gpu_cmul(${a}, ${s[l]})`;return u!=="1.0"&&(a=`(${u} * ${a})`),a},Divide:(e,n,t)=>{if(e.length===0)return"1.0";if(e.length===1)return n(e[0]);let i=P.isComplexValued(e[0]),r=e.length>=2&&P.isComplexValued(e[1]);if(!i&&!r){if(e.length===2){let u=Qe(e[0]),a=Qe(e[1]);return u!==void 0&&a!==void 0&&a!==0?jn(u/a):a===1?n(e[0]):`${n(e[0])} / ${n(e[1])}`}let s=n(e[0]);for(let u=1;u<e.length;u++)s=`${s} / ${n(e[u])}`;return s}return i&&r?`_gpu_cdiv(${n(e[0])}, ${n(e[1])})`:i&&!r?`(${n(e[0])} / ${n(e[1])})`:`_gpu_cdiv(${Ji(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?`${Ji(t)}(${jn(-e.re)}, ${jn(-e.im)})`:I(e,"ImaginaryUnit")?`${Ji(t)}(0.0, -1.0)`:`(-${n(e)})`},Abs:(e,n)=>P.isComplexValued(e[0])?`length(${n(e[0])})`:P.isNonNegative(e[0])?n(e[0]):`abs(${n(e[0])})`,Arccos:(e,n)=>P.isComplexValued(e[0])?`_gpu_cacos(${n(e[0])})`:`acos(${n(e[0])})`,Arcsin:(e,n)=>P.isComplexValued(e[0])?`_gpu_casin(${n(e[0])})`:`asin(${n(e[0])})`,Arctan:(e,n)=>P.isComplexValued(e[0])?`_gpu_catan(${n(e[0])})`:`atan(${n(e[0])})`,Ceil:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`ceil(${n(e[0])})`,Clamp:"clamp",Cos:(e,n)=>P.isComplexValued(e[0])?`_gpu_ccos(${n(e[0])})`:`cos(${n(e[0])})`,Degrees:"radians",Exp:(e,n)=>P.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)=>T2(e[0],"x",n),PointY:(e,n)=>T2(e[0],"y",n),PointZ:(e,n)=>T2(e[0],"z",n),Floor:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`floor(${n(e[0])})`,Fract:"fract",Ln:(e,n)=>P.isComplexValued(e[0])?`_gpu_cln(${n(e[0])})`:`log(${n(e[0])})`,Log2:"log2",Max:(e,n)=>gb("max",e,n),Min:(e,n)=>gb("min",e,n),ElementMax:(e,n)=>gb("max",e,n),ElementMin:(e,n)=>gb("min",e,n),Mix:"mix",If:(e,n,t)=>{if(e.length!==3)throw new Error("If: wrong number of arguments");return qp(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 I(e[1],"True")?`(${n(e[0])})`:I(e[1],"False")?w2(e[0],t):qp(n(e[1]),n(e[0]),w2(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=>c6(o))??null,r=o=>{if(o>=e.length)return w2(i,t);let s=e[o],u=e[o+1];return I(s,"True")?`(${n(u)})`:qp(n(s),n(u),r(o+2),t)};return r(0)},Match:(e,n,t)=>P.compileMatchTernary(e[0].engine,e,t,{ternary:(i,r,o)=>qp(i,r,o,t),eq:"==",noMatch:A2(t),allowStrings:!1}),Power:(e,n,t)=>{let i=e[0],r=e[1];if(i===null)throw new Error("Power: no argument");if(P.isComplexValued(i)||P.isComplexValued(r)){if(I(i,"ExponentialE"))return`_gpu_cexp(${n(r)})`;let u=Ji(t),a=P.isComplexValued(i)?n(i):`${u}(${n(i)}, 0.0)`,l=P.isComplexValued(r)?n(r):`${u}(${n(r)}, 0.0)`;return`_gpu_cpow(${a}, ${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 u=s,a=Math.abs(u),l;if(a===1)l=`(${n(i)})`;else if((I(i)||N(i))&&a<=IH){let f=n(i);l=`(${Array(a).fill(f).join(" * ")})`}else l=`_gpu_powi(${n(i)}, ${Us(a)})`;return u<0?`(1.0 / ${l})`:l}return`pow(${n(i)}, ${n(r)})`},Radians:"radians",Round:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_gpu_csin(${n(e[0])})`:`sin(${n(e[0])})`,Smoothstep:"smoothstep",Sqrt:(e,n)=>{if(P.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)=>P.isComplexValued(e[0])?`_gpu_ctan(${n(e[0])})`:`tan(${n(e[0])})`,Truncate:(e,n)=>P.isIntegerValued(e[0])?n(e[0]):`trunc(${n(e[0])})`,Real:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).x`:n(e[0]),Imaginary:(e,n)=>P.isComplexValued(e[0])?`(${n(e[0])}).y`:"0.0",Argument:(e,n,t)=>{if(P.isComplexValued(e[0])){let i=n(e[0]);return`atan(${i}.y, ${i}.x)`}return qp(`${n(e[0])} >= 0.0`,"0.0","3.14159265359",t)},Conjugate:(e,n,t)=>{if(P.isComplexValued(e[0])){let i=Ji(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(P.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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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)=>P.isComplexValued(e[0])?`_gpu_csinh(${n(e[0])})`:`sinh(${n(e[0])})`,Cosh:(e,n)=>P.isComplexValued(e[0])?`_gpu_ccosh(${n(e[0])})`:`cosh(${n(e[0])})`,Tanh:(e,n)=>P.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(P.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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(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 P.isComplexValued(e)?`_gpu_cdiv(${Ji(t)}(1.0, 0.0), _gpu_ccosh(${n(e)}))`:`(1.0 / cosh(${n(e)}))`},Arcosh:(e,n)=>P.isComplexValued(e[0])?`_gpu_cacosh(${n(e[0])})`:`acosh(${n(e[0])})`,Arsinh:(e,n)=>P.isComplexValued(e[0])?`_gpu_casinh(${n(e[0])})`:`asinh(${n(e[0])})`,Artanh:(e,n)=>P.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(I(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 a=n(e[1]),l=n(e[2]);return`(abs(_gpu_apca(${i}, ${a})) >= abs(_gpu_apca(${i}, ${l})) ? ${a} : ${l})`}let o=t?.language==="wgsl"?"vec3f":"vec3",s=`${o}(0.0)`,u=`${o}(1.0, 0.0, 0.0)`;return`((_gpu_apca(${i}, ${s}) > 50.0) ? ${s} : ${u})`},ColorToColorspace:([e,n],t)=>{if(e===null||n===null)throw new Error("ColorToColorspace: need color and space");let i=M2(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=M2(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=M2(e);if(i===null)throw new Error("Color: argument must be a string literal on GPU target");let r=Rt(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,u=r>>>8&255,a=Pn({r:o,g:s,b:u});return`${Ql(t)}(${jn(a.L)}, ${jn(a.C)}, ${jn(a.H)})`},Rgb:(e,n,t)=>{if(e.length<3)throw new Error("Rgb: need 3 components");return`_gpu_srgb_to_oklch(${Ql(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(${Ql(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(${Ql(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(${Ql(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`${Ql(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=l6(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=l6(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)=>f6("Sum",e,n,t),Product:(e,n,t)=>f6("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 u=[];for(let f=0;f<s;f++)u.push(i+f*o);return`${t.language==="wgsl"?`array<f32, ${s}>`:`float[${s}]`}(${u.map(Us).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(!I(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;k2(s,t.language);let u=Math.floor(o.ops[0].re),a=Math.floor(o.ops[1].re);if(!Number.isFinite(u)||!Number.isFinite(a))throw new Error("Loop: bounds must be finite numbers");let l=t.language==="wgsl",f=l?"i32":"int",c=l?`f32(${s})`:`float(${s})`,p=P.compile(e[0],{...t,var:g=>g===s?c:t.var(g),boundVars:P.withBoundNames(t,[s])});return`for (${l?`var ${s}: ${f}`:`${f} ${s}`} = ${u}; ${s} <= ${a}; ${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(a=>n(a)),s=`((${r.join(" + ")}) / ${Us(i)})`;return`((${r.map(a=>`(${a} - ${s}) * (${a} - ${s})`).join(" + ")}) / ${Us(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(P.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 hb(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 u=s.length,a=s[0],l=m(a)?a.nops:0;if(l===1&&s.every(f=>m(f)&&f.nops===1)){let f=s.map(c=>n(m(c)?c.ops[0]:c));return u>=2&&u<=4?`${t(u)}(${f.join(", ")})`:`${r(u)}(${f.join(", ")})`}if(u===l&&u>=2&&u<=4&&s.every(f=>m(f)&&f.nops===l)){let f=[];for(let c=0;c<l;c++){let p=s.map(d=>n(m(d)?d.ops[c]:d));f.push(`${t(u)}(${p.join(", ")})`)}return`${i(u)}(${f.join(", ")})`}return n(o)}var TH=`
|
|
148
148
|
float _gpu_gamma(float z) {
|
|
@@ -1505,13 +1505,13 @@ ${f}fn main(${g})${h} {
|
|
|
1505
1505
|
`);for(let b of u){let y=this.compileToSource(b.expression);a+=` ${b.variable} = ${y};
|
|
1506
1506
|
`}return p&&(a+=` return output;
|
|
1507
1507
|
`),a+=`}
|
|
1508
|
-
`,a}};var m6={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 g6(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=(u,a)=>`(abs((${t(u)}) - (${t(a)})) ${r} ${i})`;if(n.length===2)return o(n[0],n[1]);let s=[];for(let u=0;u<n.length-1;u++)s.push(o(n[u],n[u+1]));return`(${s.join(" and ")})`}function E6(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)):P.compile(e,n)}function _6(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)+1):`${P.compile(e,n)} + 1`}function h6(e,n,t){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);P.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 f=l.ops,c=f[0];if(!I(c))throw new Error(`${e}: index must be a symbol`);let p=c.symbol,d=f[1],g=f[2];if(d===void 0||g===void 0||I(g,"Nothing")||g.isInfinity||d.isInfinity)throw new Error(`${e}: an unbounded range is not supported`);let h=E6(d,s),b=_6(g,s);o.push(`for ${p} in range(${h}, ${b})`);let y=s;s={...y,var:x=>x===p?p:y.var(x)}}let a=`${P.compile(i,s)} ${o.join(" ")}`;return e==="Sum"?`sum(${a})`:`math.prod(${a})`}function R2(e){return(e.trim()===""?"pass":e).split(`
|
|
1508
|
+
`,a}};var m6={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 g6(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=(u,a)=>`(abs((${t(u)}) - (${t(a)})) ${r} ${i})`;if(n.length===2)return o(n[0],n[1]);let s=[];for(let u=0;u<n.length-1;u++)s.push(o(n[u],n[u+1]));return`(${s.join(" and ")})`}function E6(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)):P.compile(e,n)}function _6(e,n){return N(e)&&e.im===0&&Number.isFinite(e.re)?String(Math.floor(e.re)+1):`${P.compile(e,n)} + 1`}function h6(e,n,t){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);P.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 f=l.ops,c=f[0];if(!I(c))throw new Error(`${e}: index must be a symbol`);let p=c.symbol,d=f[1],g=f[2];if(d===void 0||g===void 0||I(g,"Nothing")||g.isInfinity||d.isInfinity)throw new Error(`${e}: an unbounded range is not supported`);let h=E6(d,s),b=_6(g,s);o.push(`for ${p} in range(${h}, ${b})`);let y=s;s={...y,var:x=>x===p?p:y.var(x),boundVars:P.withBoundNames(y,[p])}}let a=`${P.compile(i,s)} ${o.join(" ")}`;return e==="Sum"?`sum(${a})`:`math.prod(${a})`}function R2(e){return(e.trim()===""?"pass":e).split(`
|
|
1509
1509
|
`).map(t=>` ${t}`).join(`
|
|
1510
1510
|
`)}function yb(e,n){if(I(e,"Nothing"))return"";if(!m(e))return P.compile(e,n);let t=e.operator;if(t==="Break")return"break";if(t==="Continue")return"continue";if(t==="Return")return`return ${P.compile(e.ops[0],n)}`;if(t==="If"){let r=`if ${P.compile(e.ops[0],n)}:
|
|
1511
1511
|
${R2(yb(e.ops[1],n))}`;return e.ops.length>2&&(r+=`
|
|
1512
1512
|
else:
|
|
1513
1513
|
${R2(yb(e.ops[2],n))}`),r}return t==="Block"?e.ops.map(i=>yb(i,n)).filter(i=>i!=="").join(`
|
|
1514
|
-
`):t==="Loop"?S6(e.ops,n):P.compile(e,n)}function S6(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 u=i[0];if(!m(u,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let a=u.ops[0],l=u.ops[1];if(!I(a))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 f=a.symbol,c=E6(l.ops[0],n),p=_6(l.ops[1],n);r=`for ${f} in range(${c}, ${p}):`;let d=n;o={...d,var:g=>g===f?f:d.var(g)}}let s=R2(yb(t,o));return`${r}
|
|
1514
|
+
`):t==="Loop"?S6(e.ops,n):P.compile(e,n)}function S6(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 u=i[0];if(!m(u,"Element"))throw new Error("Loop: expected Element(index, Range(lo, hi))");let a=u.ops[0],l=u.ops[1];if(!I(a))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 f=a.symbol,c=E6(l.ops[0],n),p=_6(l.ops[1],n);r=`for ${f} in range(${c}, ${p}):`;let d=n;o={...d,var:g=>g===f?f:d.var(g),boundVars:P.withBoundNames(d,[f])}}let s=R2(yb(t,o));return`${r}
|
|
1515
1515
|
${s}`}var b6={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 xb(e){let n=e.type;return n.matches("list")||n.matches("indexed_collection")}var N6=`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 b6={Add:["+",11],Negate:["-",14],Subtract:["-",11],Multiply:["*",12],D
|
|
|
1545
1545
|
return _a
|
|
1546
1546
|
`;function y6(e){let n=e;return n.includes("_ce_rref(")&&(n=`${I6}
|
|
1547
1547
|
${n}`),n.includes("_ce_bcast(")&&(n=`${N6}
|
|
1548
|
-
${n}`),n}function x6(e,n,t,i){let r=t.map(s=>xb(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 Le(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 Ht(e,n,t){if(n&&m(n,"Function"))return t(n);if(n&&I(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 v6={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)=>P.isComplexValued(e[0])?`cmath.sin(${n(e[0])})`:`np.sin(${n(e[0])})`,Cos:(e,n)=>P.isComplexValued(e[0])?`cmath.cos(${n(e[0])})`:`np.cos(${n(e[0])})`,Tan:(e,n)=>P.isComplexValued(e[0])?`cmath.tan(${n(e[0])})`:`np.tan(${n(e[0])})`,Arcsin:(e,n)=>P.isComplexValued(e[0])?`cmath.asin(${n(e[0])})`:`np.arcsin(${n(e[0])})`,Arccos:(e,n)=>P.isComplexValued(e[0])?`cmath.acos(${n(e[0])})`:`np.arccos(${n(e[0])})`,Arctan:(e,n)=>P.isComplexValued(e[0])?`cmath.atan(${n(e[0])})`:`np.arctan(${n(e[0])})`,Arctan2:"np.arctan2",Sinh:(e,n)=>P.isComplexValued(e[0])?`cmath.sinh(${n(e[0])})`:`np.sinh(${n(e[0])})`,Cosh:(e,n)=>P.isComplexValued(e[0])?`cmath.cosh(${n(e[0])})`:`np.cosh(${n(e[0])})`,Tanh:(e,n)=>P.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)=>P.isComplexValued(e[0])?`cmath.exp(${n(e[0])})`:`np.exp(${n(e[0])})`,Ln:(e,n)=>P.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":P.isComplexValued(e[0])||P.isComplexValued(e[1])?`(${n(e[0])} ** ${n(e[1])})`:`np.power(${n(e[0])}, ${n(e[1])})`,Sqrt:(e,n)=>P.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)=>P.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)=>x6("np.min","np.minimum",e,n),Max:(e,n)=>x6("np.max","np.maximum",e,n),ElementMax:(e,n)=>{if(!e.some(xb)){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(xb)){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(xb)?`_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)=>h6("Sum",e,t),Product:(e,n,t)=>h6("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)=>g6("Equal",e,n),NotEqual:(e,n)=>g6("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 I(e[1],"True")?`(${n(e[0])})`:I(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 I(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)=>S6(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=>fn(s)||"_"),o=P.compile(i.canonical,{...t,var:s=>r.includes(s)?s:t.var(s)});return`(lambda ${r.join(", ")}: ${o})`},Length:(e,n)=>`len(${Le("Length",e[0],n)})`,Count:(e,n)=>`len(${Le("Count",e[0],n)})`,IsEmpty:(e,n)=>`(len(${Le("IsEmpty",e[0],n)}) == 0)`,At:(e,n)=>{let t=Le("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'))(${Le("First",e[0],n)})`,Second:(e,n)=>`(lambda _l: _l[1] if len(_l) > 1 else float('nan'))(${Le("Second",e[0],n)})`,Third:(e,n)=>`(lambda _l: _l[2] if len(_l) > 2 else float('nan'))(${Le("Third",e[0],n)})`,Last:(e,n)=>`(lambda _l: _l[-1] if len(_l) > 0 else float('nan'))(${Le("Last",e[0],n)})`,Rest:(e,n)=>`${Le("Rest",e[0],n)}[1:]`,Most:(e,n)=>`${Le("Most",e[0],n)}[:-1]`,Take:(e,n)=>{let t=Le("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=Le("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)=>`${Le("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(${Le("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])])(${Le("Ordering",e[0],n)})`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`*${Le("Join",t,n,i+1)}`).join(", ")}]`,Append:(e,n)=>{let t=Le("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[*${t}, ${n(e[1])}]`},IndexOf:(e,n)=>{let t=Le("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]&&ea("Contains",e[0]);let t=Le("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]&&ea("Unique",e[0]),`list(dict.fromkeys(${Le("Unique",e[0],n)}))`),Zip:(e,n)=>e.length===0?"[]":`[list(_t) for _t in zip(${e.map((i,r)=>Le("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=Le("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}])(${Ht("Map",e[1],n)})`},Filter:(e,n)=>{let t=Le("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)])(${Ht("Filter",e[1],n)})`},CountIf:(e,n)=>{let t=Le("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)))(${Ht("CountIf",e[1],n)})`},Find:(e,n)=>{let t=Le("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')))(${Ht("Find",e[1],n)})`},IndexWhere:(e,n)=>{let t=Le("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))(${Ht("IndexWhere",e[1],n)})`},Position:(e,n)=>{let t=Le("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)])(${Ht("Position",e[1],n)})`},Any:(e,n)=>{let t=Le("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}))(${Ht("Any",e[1],n)})`},All:(e,n)=>{let t=Le("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}))(${Ht("All",e[1],n)})`},TakeWhile:(e,n)=>{let t=Le("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))])(${Ht("TakeWhile",e[1],n)}, ${t})`},DropWhile:(e,n)=>{let t=Le("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)):])(${Ht("DropWhile",e[1],n)}, ${t})`},FlatMap:(e,n)=>{let t=Le("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))])(${Ht("FlatMap",e[1],n)}, ${t})`},Reduce:(e,n)=>{let t=Le("Reduce",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Reduce: missing combiner");let o=I(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||I(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(${Ht("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=Le("Scan",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Scan: missing combiner");let s=(I(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||I(i)?Ht("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=Ht("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=Ht("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(!P.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 ea("Element",e[1]),`(${n(e[0])} in ${Le("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])]))(${Le("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=Le("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(${Le("Trace",e[0],n)})))`}},jp=class{includeImports;useScipy;constructor(n={}){this.includeImports=n.includeImports??!1,this.useScipy=n.useScipy??!1}getOperators(){return b6}getFunctions(){return v6}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=>b6[t],functions:t=>v6[t],var:t=>m6[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 x6(e,n,t,i){let r=t.map(s=>xb(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 Le(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 Ht(e,n,t){if(n&&m(n,"Function"))return t(n);if(n&&I(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 v6={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)=>P.isComplexValued(e[0])?`cmath.sin(${n(e[0])})`:`np.sin(${n(e[0])})`,Cos:(e,n)=>P.isComplexValued(e[0])?`cmath.cos(${n(e[0])})`:`np.cos(${n(e[0])})`,Tan:(e,n)=>P.isComplexValued(e[0])?`cmath.tan(${n(e[0])})`:`np.tan(${n(e[0])})`,Arcsin:(e,n)=>P.isComplexValued(e[0])?`cmath.asin(${n(e[0])})`:`np.arcsin(${n(e[0])})`,Arccos:(e,n)=>P.isComplexValued(e[0])?`cmath.acos(${n(e[0])})`:`np.arccos(${n(e[0])})`,Arctan:(e,n)=>P.isComplexValued(e[0])?`cmath.atan(${n(e[0])})`:`np.arctan(${n(e[0])})`,Arctan2:"np.arctan2",Sinh:(e,n)=>P.isComplexValued(e[0])?`cmath.sinh(${n(e[0])})`:`np.sinh(${n(e[0])})`,Cosh:(e,n)=>P.isComplexValued(e[0])?`cmath.cosh(${n(e[0])})`:`np.cosh(${n(e[0])})`,Tanh:(e,n)=>P.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)=>P.isComplexValued(e[0])?`cmath.exp(${n(e[0])})`:`np.exp(${n(e[0])})`,Ln:(e,n)=>P.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":P.isComplexValued(e[0])||P.isComplexValued(e[1])?`(${n(e[0])} ** ${n(e[1])})`:`np.power(${n(e[0])}, ${n(e[1])})`,Sqrt:(e,n)=>P.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)=>P.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)=>x6("np.min","np.minimum",e,n),Max:(e,n)=>x6("np.max","np.maximum",e,n),ElementMax:(e,n)=>{if(!e.some(xb)){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(xb)){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(xb)?`_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)=>h6("Sum",e,t),Product:(e,n,t)=>h6("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)=>g6("Equal",e,n),NotEqual:(e,n)=>g6("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 I(e[1],"True")?`(${n(e[0])})`:I(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 I(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)=>S6(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=>fn(s)||"_"),o=P.compile(i.canonical,{...t,var:s=>r.includes(s)?s:t.var(s),boundVars:P.withBoundNames(t,r)});return`(lambda ${r.join(", ")}: ${o})`},Length:(e,n)=>`len(${Le("Length",e[0],n)})`,Count:(e,n)=>`len(${Le("Count",e[0],n)})`,IsEmpty:(e,n)=>`(len(${Le("IsEmpty",e[0],n)}) == 0)`,At:(e,n)=>{let t=Le("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'))(${Le("First",e[0],n)})`,Second:(e,n)=>`(lambda _l: _l[1] if len(_l) > 1 else float('nan'))(${Le("Second",e[0],n)})`,Third:(e,n)=>`(lambda _l: _l[2] if len(_l) > 2 else float('nan'))(${Le("Third",e[0],n)})`,Last:(e,n)=>`(lambda _l: _l[-1] if len(_l) > 0 else float('nan'))(${Le("Last",e[0],n)})`,Rest:(e,n)=>`${Le("Rest",e[0],n)}[1:]`,Most:(e,n)=>`${Le("Most",e[0],n)}[:-1]`,Take:(e,n)=>{let t=Le("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=Le("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)=>`${Le("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(${Le("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])])(${Le("Ordering",e[0],n)})`},Join:(e,n)=>e.length===0?"[]":`[${e.map((t,i)=>`*${Le("Join",t,n,i+1)}`).join(", ")}]`,Append:(e,n)=>{let t=Le("Append",e[0],n);if(e[1]==null)throw new Error("Append: missing value");return`[*${t}, ${n(e[1])}]`},IndexOf:(e,n)=>{let t=Le("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]&&ea("Contains",e[0]);let t=Le("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]&&ea("Unique",e[0]),`list(dict.fromkeys(${Le("Unique",e[0],n)}))`),Zip:(e,n)=>e.length===0?"[]":`[list(_t) for _t in zip(${e.map((i,r)=>Le("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=Le("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}])(${Ht("Map",e[1],n)})`},Filter:(e,n)=>{let t=Le("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)])(${Ht("Filter",e[1],n)})`},CountIf:(e,n)=>{let t=Le("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)))(${Ht("CountIf",e[1],n)})`},Find:(e,n)=>{let t=Le("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')))(${Ht("Find",e[1],n)})`},IndexWhere:(e,n)=>{let t=Le("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))(${Ht("IndexWhere",e[1],n)})`},Position:(e,n)=>{let t=Le("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)])(${Ht("Position",e[1],n)})`},Any:(e,n)=>{let t=Le("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}))(${Ht("Any",e[1],n)})`},All:(e,n)=>{let t=Le("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}))(${Ht("All",e[1],n)})`},TakeWhile:(e,n)=>{let t=Le("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))])(${Ht("TakeWhile",e[1],n)}, ${t})`},DropWhile:(e,n)=>{let t=Le("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)):])(${Ht("DropWhile",e[1],n)}, ${t})`},FlatMap:(e,n)=>{let t=Le("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))])(${Ht("FlatMap",e[1],n)}, ${t})`},Reduce:(e,n)=>{let t=Le("Reduce",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Reduce: missing combiner");let o=I(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||I(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(${Ht("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=Le("Scan",e[0],n),i=e[1],r=e[2];if(i==null)throw new Error("Scan: missing combiner");let s=(I(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||I(i)?Ht("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=Ht("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=Ht("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(!P.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 ea("Element",e[1]),`(${n(e[0])} in ${Le("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])]))(${Le("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=Le("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(${Le("Trace",e[0],n)})))`}},jp=class{includeImports;useScipy;constructor(n={}){this.includeImports=n.includeImports??!1,this.useScipy=n.useScipy??!1}getOperators(){return b6}getFunctions(){return v6}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=>b6[t],functions:t=>v6[t],var:t=>m6[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 m6[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}`),P.buildInterpreterFallback(n,r,"python",this.createTarget(),t.vars?new Set(Object.keys(t.vars)):void 0)}}compileOrThrow(n,t={}){n=ro(n);let i=t.vars,r=this.createTarget({var:this.makeVarResolver(i)}),o=y6(P.compile(n,r));this.includeImports&&(o=this.withImports(o));let s={target:"python",success:!0,code:o};return P.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)=>nf("_IA.equal",e,n),NotEqual:(e,n)=>nf("_IA.notEqual",e,n),LessEqual:(e,n)=>nf("_IA.lessEqual",e,n),GreaterEqual:(e,n)=>nf("_IA.greaterEqual",e,n),Less:(e,n)=>nf("_IA.less",e,n),Greater:(e,n)=>nf("_IA.greater",e,n),And:(e,n)=>q6("_IA.and",e,n),Or:(e,n)=>q6("_IA.or",e,n),Not:(e,n)=>`_IA.not(${n(e[0])})`},gY=100;function hY(e){e.operator;let n=e,t=I(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 V6(e,n,t){return n!==void 0?String(n):`Math.floor(((_b) => (_b && _b.value ? _b.value.hi : _b.hi))(${P.compile(e,t)}))`}function j6(e,n,t,i){if(!n[0])throw new Error(`${e}: no body`);if(!n[1])throw new Error(`${e}: no indexing set`);if(P.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:u,upperNum:a}=hY(n[1]),l=e==="Sum",f=l?"_IA.add":"_IA.mul",c=l?"_IA.point(0)":"_IA.point(1)",p=u!==void 0&&a!==void 0;if(p&&u>a)return c;if(p&&a-u+1<=gY){let x=[];for(let S=u;S<=a;S++){let _={...i,var:w=>w===r?`_IA.point(${S})`:i.var(w),boundVars:P.withBoundNames(i,[r])};x.push(P.compile(n[0],_))}let v=x[x.length-1];for(let S=x.length-2;S>=0;S--)v=`${f}(${x[S]}, ${v})`;return v}let d=V6(o,u,i),g=V6(s,a,i),h=P.tempVar(),b=P.compile(n[0],{...i,var:y=>y===r?`_IA.point(${r})`:i.var(y),boundVars:P.withBoundNames(i,[r])});return`(() => { let ${h} = ${c}; const _upper = ${g}; for (let ${r} = ${d}; ${r} <= _upper; ${r}++) { ${h} = ${f}(${h}, ${b}); } return ${h}; })()`}var tS=class extends Function{IA=B6;constructor(n,t=""){return super("_IA","_",t?`${t};return ${n}`:`return ${n}`),new Proxy(this,{apply:(i,r,o)=>{try{let s=o.map(G6);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 iS(e){return e!==null&&typeof e=="object"}function z6(e){return iS(e)&&"lo"in e&&"hi"in e}function bY(e){return typeof e=="number"?{lo:e,hi:e}:{kind:"entire"}}function J6(e){if(z6(e))return(Number(e.lo)+Number(e.hi))/2;if(iS(e)){let n={};for(let[t,i]of Object.entries(e))n[t]=J6(i);return n}return e}function G6(e){if(e==null||z6(e))return e;if(iS(e)){let n={};for(let[t,i]of Object.entries(e))n[t]=G6(i);return n}return typeof e=="number"?{lo:e,hi:e}:e}var Hp=class{getOperators(){return mY}getFunctions(){return nS}createTarget(n={}){return{language:"interval-javascript",operators:()=>{},functions:t=>nS[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=P.buildInterpreterFallback(n,t,"interval-js",this.createTarget(),i.vars?new Set(Object.keys(i.vars)):void 0),o=r.run;return{...r,run:(...u)=>bY(o(...u.map(J6)))}}compileOrThrow(n,t={}){n=ro(n);let{functions:i,vars:r,preamble:o}=t,s=n.unknowns,u={},a="";if(i)for(let[c,p]of Object.entries(i))typeof p=="function"?(a+=`const ${c} = ${p.toString()};
|
|
1581
1581
|
`,u[c]=c):typeof p=="string"&&(u[c]=p);let l=this.createTarget({functions:c=>u?.[c]?u[c]:nS[c],var:c=>{if(r&&c in r)return r[c];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(c in p)return p[c];if(s.includes(c))return`_.${c}`;if(n.engine._getSymbolValue(c)===void 0)return`_.${c}`},preamble:(o??"")+a,userFunctions:{defs:new Map,compiling:new Set}}),f=yY(n,l);return P.withReferences(f,n,l,r?new Set(Object.keys(r)):void 0)}};function yY(e,n){let t;try{t=P.compile(e,n)}catch(s){return{target:"interval-js",success:!1,code:"",error:s.message}}let i=P.userFunctionsPreamble(n),r=i?n.preamble?`${n.preamble}
|
|
1582
|
-
${i}`:i:n.preamble,o=new tS(t,r);return{target:"interval-js",success:!0,code:t,calling:"expression",run:o}}var Cb=class{_targets=new Map;register(n,t){DD(n),FD(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 Bp),this.register("glsl",new Vp),this.register("wgsl",new bb),this.register("python",new jp),this.register("interval-js",new Hp)}};var Ab=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 kb=class{_generation=0;_mutationGeneration=0;_ephemeralWriteDepth=0;_tracker=new Ab;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 xY(e){return!!(e===void 0||e==="Number"||e===!0||Array.isArray(e)&&e.includes("Number"))}function U6(e,n,t,i){let r=i?.canonical??!0,o=i?.metadata,s=t.normalize(),u=s.toLowerCase();if(u==="infinity"||u==="+infinity")return e.PositiveInfinity;if(u==="-infinity")return e.NegativeInfinity;if(e.strict&&!An(s))return e.error(["invalid-symbol",yi(s)],s);if(!r)return new fr(e,s,{metadata:o});if(e._isShadowedParameter(s)){let c=e._shadowedParameterType(s);if(c!==void 0){let d=e._shadowedParameterDef(s);if(d!==void 0)return new fr(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:c,inferred:!1},g);return e._setShadowedParameterDef(s,h),new fr(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 fr(e,s,{metadata:o,def:p})}let a=n[s];if(a)return a;let l=e.lookupDefinition(s);if(ie(l)&&l.value.holdUntil==="never")return l.value.value??e.Nothing;if(l)return new fr(e,s,{metadata:o,def:l});let f=e.context.lexicalScope;for(;f.noAutoDeclare&&f.parent;)f=f.parent;return l=e._declareSymbolValue(s,{type:"unknown",inferred:!0},f),new fr(e,s,{metadata:o,def:l})}function Z6(e,n,t,i){let r=i?.metadata;if(!xY(i?.canonical)&&vr(t))return e._fn("Rational",[e.number(t[0]),e.number(t[1])],{...r,canonical:!1});let s=Yg(e,t);if(r===void 0){if(typeof s=="number"){let u=s;if(u===1)return e.One;if(u===0)return e.Zero;if(u===-1)return e.NegativeOne;if(u===2)return e.Two;if(Number.isInteger(u)&&n[u]!==void 0)return n[u]??=new kn(e,s),n[u];if(Number.isNaN(u))return e.NaN;if(!Number.isFinite(u))return u<0?e.NegativeInfinity:e.PositiveInfinity}else if(s instanceof ze){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 kn(e,s,{metadata:r})}var tf=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 Rb=class{_precision;_angularUnit;_tolerance;_bignumTolerance;_negBignumTolerance;constructor(n){let t=n?.precision??p0;t==="machine"&&(t=Math.floor(Ui)),this._precision=t,E.precision=t,this._angularUnit=n?.angularUnit??"rad",this._tolerance=da,this._bignumTolerance=new E(da),this._negBignumTolerance=new E(-da),this.setTolerance(n?.tolerance??"auto")}get precision(){return this._precision}setPrecision(n){let t=n;if(t==="machine"&&(t=Ui),t==="auto"&&(t=p0),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,Ui),E.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=da),(!Number.isFinite(t)||t<0)&&(t=Math.pow(10,-this._precision+2)),this._tolerance=t,this._bignumTolerance=new E(t),this._negBignumTolerance=new E(-t)}get bignumTolerance(){return this._bignumTolerance}get negBignumTolerance(){return this._negBignumTolerance}get bignumNaN(){return E.NAN}get bignumZero(){return E.ZERO}get bignumOne(){return E.ONE}get bignumTwo(){return E.TWO}get bignumHalf(){return E.HALF}get bignumPi(){return E.PI}get bignumNegativeOne(){return E.NEGATIVE_ONE}bignum(n){if(n instanceof E)return n;try{return new E(n)}catch(t){t instanceof Error?console.error(t.message):console.error(String(t))}return E.NAN}};var Pb=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 Ce({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 vY(e){if(typeof e!="string")return LD(e),e;let n=Kh.find(t=>t.name===e);if(!n)throw new Error(`Unknown standard library: "${e}"`);return n}function H6(e){return e?eb(e.map(vY)):[...nb()]}function Y6(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)xD(e,o)}}function Yp(e,n){let t=e[n];if(!t)throw new Error(`Common symbol "${n}" failed to initialize`);return t}var Db=class{constructor(n){this.engine=n}engine;initializeCommonNumbers(){return{Zero:new kn(this.engine,0),One:new kn(this.engine,1),Half:new kn(this.engine,{rational:[1,2]}),NegativeOne:new kn(this.engine,-1),Two:new kn(this.engine,2),NaN:new kn(this.engine,Number.NaN),PositiveInfinity:new kn(this.engine,Number.POSITIVE_INFINITY),NegativeInfinity:new kn(this.engine,Number.NEGATIVE_INFINITY),I:new kn(this.engine,{im:1}),ComplexInfinity:new kn(this.engine,{re:1/0,im:1/0})}}bootstrapLibraries(n){let t=H6(n);Y6(this.engine,t)}initializeCommonSymbolBindings(n){return U4(this.engine,n),{True:Yp(n,"True"),False:Yp(n,"False"),Pi:Yp(n,"Pi"),E:Yp(n,"ExponentialE"),Nothing:Yp(n,"Nothing")}}};function EY(e){let n=[],t=e;for(;t;)t.types&&n.push(...Object.keys(t.types)),t=t.parent;return n}function _Y(e,n){let t=e;for(;t;){if(t.types?.[n])return t.types[n];t=t.parent}}function W6(e){return{get names(){return EY(e.context.lexicalScope)},resolve(n){return _Y(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 Ob(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&&$d(t)?r=e.function("LatexString",[e.string(ss(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 Q6(e,n,t,i){return t?Ob(e,["incompatible-type",le(n),t.toString()],i):Ob(e,["incompatible-type",le(n)],i)}var rS=null,oS=null;function X6(e){oS=e}function Hs(){if(!rS){if(!oS)throw new Error("ComputeEngine factory not registered. Import from the main module.");rS=oS()}return rS}function na(e,n){if(typeof e=="string"){let t=Hs();return t.parse(e,{strict:n?.strict??!1})??t.expr("Nothing")}return gd(e)?e:Hs().expr(e)}function sS(e,n){return Hs().expr(e,n)}function uS(e,n){return na(e,n).simplify(n)}function aS(e,n){return na(e,n).evaluate()}function lS(e,n){return na(e,n).N()}function fS(e,n){Hs().declare(e,n)}function cS(e,n){Hs().assign(e,n)}function pS(e,n){return Ae(na(e,n))}function dS(e,n,t){return na(e,t).solve(n)}function mS(e,n){return Ar(na(e,n))}function gS(e,n){return sr(na(e,n))}var SY=/^(Sin|Cos|Tan|Cot|Sec|Csc)$/;function Fb(e){return SY.test(e.operator)?!0:m(e)?e.ops.some(Fb):!1}function Ys(e,...n){return n.includes(e.operator)?!0:m(e)?e.ops.some(t=>Ys(t,...n)):!1}function wn(e,n){let t=e.engine;if(m(e)&&e.ops.length>0){let i=e,r=i.ops.map(s=>wn(s,n));r.some((s,u)=>s!==i.ops[u])&&(e=t._fn(i.operator,r))}return n(e)??e}function hS(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 NY(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 i7(e){return wn(e,NY)}function IY(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 r7(e){return wn(e,IY)}function wY(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"&&hS(t,i))return m(t)?n._fn("Tan",[t.op1]):void 0;if(t.operator==="Cos"&&i.operator==="Sin"&&hS(t,i))return m(t)?n._fn("Cot",[t.op1]):void 0}}function o7(e){return wn(e,wY)}function TY(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 MY(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(!i)return;let r=TY(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 s7(e){return wn(e,MY)}function CY(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 bS(e){return wn(e,CY)}function AY(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 u7(e){return wn(e,AY)}function kY(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 a7(e){return wn(e,kY)}function RY(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 K6(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 K6(n,o.ops)}}}if(m(e,"Add")&&e.ops.length===2){let i,r,o=!1,s=u=>u.re===-.5&&u.im===0;for(let u of e.ops){if(t(u)){i=u;continue}let a=u,l=!1;if(m(u,"Negate")&&(l=!0,a=u.op1),m(a,"Divide")&&a.op2?.isSame(2)){let f=a.op1;if(f?.operator==="Cos"){r=f,o=l;continue}}if(m(a,"Multiply")){let f=a.ops.findIndex(p=>t(p));if(f>=0){let p=a.ops.filter((d,g)=>g!==f);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=l;continue}}let c=a.ops.findIndex(p=>s(p));if(c>=0){let p=a.ops.filter((d,g)=>g!==c);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=!l;continue}}}}if(i&&r){if(!m(r))return;let u=r.op1;if(!u)return;let a;if(m(u,"Multiply")){let l=u.ops.findIndex(f=>f.isSame(2));if(l>=0){let f=u.ops.filter((c,p)=>p!==l);a=f.length===1?f[0]:n._fn("Multiply",f)}}return a?o?n._fn("Sin",[a]).pow(2):n._fn("Cos",[a]).pow(2):void 0}}}function K6(e,n){let t=-1,i=-1,r=!1;for(let a=0;a<n.length;a++)if(n[a].isSame(1))t=a;else if(n[a].operator==="Cos")i=a,r=!1;else if(n[a].operator==="Negate"){let l=n[a];m(l)&&l.op1?.operator==="Cos"&&(i=a,r=!0)}if(t<0||i<0)return;let o;if(r){let a=n[i];if(!m(a))return;o=a.op1}else o=n[i];if(!m(o))return;let s=o.op1;if(!s)return;let u;if(m(s,"Multiply")){let a=s.ops.findIndex(l=>l.isSame(2));if(a>=0){let l=s.ops.filter((f,c)=>c!==a);u=l.length===1?l[0]:e._fn("Multiply",l)}}if(u)return r?e._fn("Sin",[u]).pow(2):e._fn("Cos",[u]).pow(2)}function yS(e){return wn(e,RY)}function PY(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 u=o.op1,a=s.op1;if(!u||!a)continue;let l;if(o.operator==="Sin"&&s.operator==="Cos"?l=n._fn("Sin",[u.add(a)]).add(n._fn("Sin",[u.sub(a)])).div(2):o.operator==="Cos"&&s.operator==="Sin"?l=n._fn("Sin",[u.add(a)]).sub(n._fn("Sin",[u.sub(a)])).div(2):o.operator==="Cos"&&s.operator==="Cos"?l=n._fn("Cos",[u.add(a)]).add(n._fn("Cos",[u.sub(a)])).div(2):o.operator==="Sin"&&s.operator==="Sin"&&(l=n._fn("Cos",[u.sub(a)]).sub(n._fn("Cos",[u.add(a)])).div(2)),l){let f=t.filter((c,p)=>p!==i&&p!==r);return f.length===0?l:l.mul(f.length===1?f[0]:n._fn("Multiply",f))}}}function l7(e){return wn(e,PY)}function DY(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],u;if(o.operator==="Sin"&&s.operator==="Sin"){if(!m(o)||!m(s))continue;let a=o.op1,l=s.op1;if(a&&l){let f=a.add(l).div(2),c=a.sub(l).div(2);u=n._fn("Sin",[f]).mul(n._fn("Cos",[c])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Cos"){if(!m(o)||!m(s))continue;let a=o.op1,l=s.op1;if(a&&l){let f=a.add(l).div(2),c=a.sub(l).div(2);u=n._fn("Cos",[f]).mul(n._fn("Cos",[c])).mul(2)}}else if(o.operator==="Sin"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Sin")continue;let a=s.op1;if(!m(a))continue;let l=o.op1,f=a.op1;if(l&&f){let c=l.add(f).div(2),p=l.sub(f).div(2);u=n._fn("Cos",[c]).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 a=s.op1;if(!m(a))continue;let l=o.op1,f=a.op1;if(l&&f){let c=l.add(f).div(2),p=l.sub(f).div(2);u=n._fn("Sin",[c]).mul(n._fn("Sin",[p])).mul(-2)}}if(u){let a=t.filter((l,f)=>f!==i&&f!==r);return a.length===0?u:u.add(a.length===1?a[0]:n._fn("Add",a))}}}function Lb(e){return wn(e,DY)}function OY(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 f7(e){return wn(e,OY)}function FY(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],u=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Sin"&&A.operator==="Cos"?{sin:M,cos:A}:M.operator==="Cos"&&A.operator==="Sin"?{sin:A,cos:M}:null},a=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Cos"&&A.operator==="Cos"?{cos1:M,cos2:A}:null},l=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Sin"&&A.operator==="Sin"?{sin1:M,sin2:A}:null},f=_=>m(_)?_.op1:void 0,c=u(o),p=u(s),d=m(o,"Negate")&&o.op1?u(o.op1):null,g=m(s,"Negate")&&s.op1?u(s.op1):null;if(c&&p){let _=f(c.sin),w=f(c.cos),M=f(p.sin),A=f(p.cos);if(_&&w&&M&&A&&_.isSame(A)&&w.isSame(M)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(c&&g){let _=f(c.sin),w=f(c.cos),M=f(g.sin),A=f(g.cos);if(_&&w&&M&&A&&_.isSame(A)&&w.isSame(M)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(d&&p){let _=f(d.sin),w=f(d.cos),M=f(p.sin),A=f(p.cos);if(_&&w&&M&&A&&M.isSame(w)&&A.isSame(_)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[M.sub(A)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}let h=a(o),b=a(s),y=l(o),x=l(s),v=m(o,"Negate")&&o.op1?l(o.op1):null,S=m(s,"Negate")&&s.op1?l(s.op1):null;if(h&&S){let _=f(h.cos1),w=f(h.cos2),M=f(S.sin1),A=f(S.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(v&&b){let _=f(b.cos1),w=f(b.cos2),M=f(v.sin1),A=f(v.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(h&&x){let _=f(h.cos1),w=f(h.cos2),M=f(x.sin1),A=f(x.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(y&&b){let _=f(b.cos1),w=f(b.cos2),M=f(y.sin1),A=f(y.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}}}function $b(e){return wn(e,FY)}function LY(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((a,l)=>l!==o),u=s.length===1?s[0]:n._fn("Multiply",s);return t==="Sin"?n._fn("Sin",[u]).mul(n._fn("Cos",[u])).mul(2):n._fn("Cos",[u]).pow(2).mul(2).sub(n.One)}}}function xS(e){return wn(e,LY)}function $Y(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((u,a)=>a!==i),o,s;for(let u of r)u.operator==="Sin"&&!o?o=u:u.operator==="Cos"&&!s&&(s=u);if(o&&s&&hS(o,s)){if(!m(o))return;let u=r.filter(l=>l!==o&&l!==s),a=n._fn("Sin",[o.op1.mul(2)]);return u.length===0?a:a.mul(u.length===1?u[0]:n._fn("Multiply",u))}}}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 a=t.op1,l=i.op1;if(m(a)&&m(l)){let f=l.op1;if(m(f)){let c=a.op1,p=f.op1;if(c&&p&&c.isSame(p))return n._fn("Cos",[c.mul(2)])}}}let r=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Cos"&&c.op2?.isSame(2)){let p=c.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=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Sin"&&c.op2?.isSame(2)){let p=c.op1;if(m(p))return p.op1}};if(t.isSame(1)&&m(i,"Negate")&&i.op1){let a=s(i.op1);if(a)return n._fn("Cos",[a.mul(2)])}if(i.isSame(1)&&m(t,"Negate")&&t.op1){let a=s(t.op1);if(a)return n._fn("Cos",[a.mul(2)])}let u=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(-2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Sin"&&c.op2?.isSame(2)){let p=c.op1;if(m(p))return p.op1}};if(t.isSame(1)){let a=u(i);if(a)return n._fn("Cos",[a.mul(2)])}if(i.isSame(1)){let a=u(t);if(a)return n._fn("Cos",[a.mul(2)])}}}function c7(e){return wn(e,$Y)}function e7(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(u=>u.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 BY(e){let n=e.engine;if(!m(e,"Add")||e.ops.length!==2)return;let t=e7(e.ops[0]),i=e7(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 p7(e){return wn(e,BY)}function qY(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 d7(e){return wn(e,qY)}var VY=[{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 jY(e,n=1e-10){for(let t of VY)if(Math.abs(t.value-e)<n)return t.angle}function zY(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 n7(e){if(m(e,"Multiply")){let n=!1,t;for(let i of e.ops)if(I(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(I(e,"Pi"))return[1,1]}function JY(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 v=t[x];if(m(v,"Tan")&&v.op1)i.push({arg:v.op1,index:x});else{let S=zY(v);S&&(r={coef:S[0],arg1:S[1],arg2:S[2],index:x})}}if(i.length!==2||!r)return;let[o,s]=i,u=o.arg.isSame(r.arg1)||o.arg.isSame(r.arg2),a=s.arg.isSame(r.arg1)||s.arg.isSame(r.arg2),l=o.arg.isSame(r.arg2)||o.arg.isSame(r.arg1),f=s.arg.isSame(r.arg2)||s.arg.isSame(r.arg1);if(!(u&&f||a&&l))return;let c=-r.coef;if(c<=0)return;let p=jY(c);if(!p)return;let d=n7(o.arg),g=n7(s.arg);if(!d||!g)return;let h=t7(t7(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 t7(e,n){return Math.abs(e*n)/GY(e,n)}function GY(e,n){for(e=Math.abs(e),n=Math.abs(n);n;){let t=n;n=e%n,e=t}return e}function m7(e){return wn(e,JY)}function UY(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 u=o.op1,a=s.op1;if(!(!u||!a)){if(o.operator==="Tan"&&s.operator==="Tan"){let l=o,f=s,c=n._fn("Cot",[u.add(a)]),p=n.One.sub(l.add(f).mul(c)),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,f=s,c=n._fn("Cot",[u.add(a)]),p=n.One.add(l.add(f).mul(c)),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 g7(e){return wn(e,UY)}function ZY(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 h7(e){return wn(e,ZY)}function HY(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,u=-1,a=!1;for(let p=0;p<t.length;p++){let d=t[p];d.isSame(1)?(s=p,a=!1):d.isSame(-1)||m(d,"Negate")&&d.op1?.isSame(1)?(s=p,a=!0):m(d,"Power")&&d.op2?.isSame(2)&&(u=p)}if(s<0||u<0)return;let l=t[u];if(!m(l))return;let f=l.op1;if(!f||!m(f))return;let c=f.op1;if(c){if(f.operator==="Sec"&&a)return n._fn("Tan",[c]).pow(2);if(f.operator==="Csc"&&a)return n._fn("Cot",[c]).pow(2);if(f.operator==="Tan"&&!a)return n._fn("Sec",[c]).pow(2);if(f.operator==="Cot"&&!a)return n._fn("Csc",[c]).pow(2)}}function vS(e){return wn(e,HY)}function YY(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((u,a)=>a!==t),s=o.length===1?o[0]:n._fn("Multiply",o);return[r,i,s]}}return[1,n.One,e]}function WY(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 M of t)if(m(M,"Cos")&&M.op1){let A=YY(M.op1);A?i.push({arg:A[2],numericMult:A[0],symbolicCoeff:A[1]}):i.push({arg:M.op1,numericMult:1,symbolicCoeff:n.One})}else r.push(M);if(i.length<2)return;let o=i[0].arg,s=i.filter(M=>M.arg.isSame(o)),u=i.filter(M=>!M.arg.isSame(o));if(s.length<2)return;s.sort((M,A)=>M.numericMult-A.numericMult);let a=[],l=[],f=[...s],c=f[0].numericMult;if(c>0){a.push(f[0]);let M=new Set([0]),A=c*2;for(;;){let k=f.findIndex((D,q)=>!M.has(q)&&Math.abs(D.numericMult-A)<1e-10);if(k===-1)break;a.push(f[k]),M.add(k),A*=2}l=f.filter((k,D)=>!M.has(D))}if(a.length<2)return;let p=a[0].numericMult,d=[...r];for(let M of l){let A=M.symbolicCoeff.isSame(n.One)?M.arg:n._fn("Multiply",[M.symbolicCoeff,M.arg]);d.push(n._fn("Cos",[A]))}for(let M of u){let A=M.symbolicCoeff.isSame(n.One)?M.arg:n._fn("Multiply",[M.symbolicCoeff,M.arg]);d.push(n._fn("Cos",[A]))}let g=a.length,h=a[0].symbolicCoeff,b=Math.pow(2,g);if(I(o,"Pi")){let M=1/(b+1);if(Math.abs(p-M)<1e-10){let A=n.number([1,b]);return d.length===0?A:A.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]),v=n._fn("Multiply",[y,o]),S=n._fn("Sin",[v]),_=n._fn("Sin",[x]),w=S.div(n.number(b).mul(_));return d.length===0?w:w.mul(d.length===1?d[0]:n._fn("Multiply",d))}function b7(e){return wn(e,WY)}function QY(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 XY(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 u=t[s],a=QY(u);a?i.push({...a,index:s}):typeof u.re=="number"&&u.im===0&&N(u)?o.push({value:u.re,index:s}):r.push({expr:u,index:s})}for(let s=0;s<i.length;s++)for(let u=s+1;u<i.length;u++){let a=i[s],l=i[u];if(a.arg.isSame(l.arg)&&(a.func==="Sin"&&l.func==="Cos"||a.func==="Cos"&&l.func==="Sin")&&Math.abs(a.coef-l.coef)<1e-10){let f=a.coef,c=new Set([a.index,l.index]),p=t.filter((d,g)=>!c.has(g));return p.length===0?n.number(f):f===1?n._fn("Add",[n.One,...p]):n._fn("Add",[n.number(f),...p])}}for(let s of i)if(s.coef<0){let u=Math.abs(s.coef);for(let a of o)if(Math.abs(a.value-u)<1e-10){let l=new Set([s.index,a.index]),f=t.filter((d,g)=>!l.has(g)),c=s.func==="Sin"?"Cos":"Sin",p=n._fn(c,[s.arg]).pow(2).mul(u);return f.length===0?p:n._fn("Add",[p,...f])}}}function y7(e){return wn(e,XY)}var KY=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]);function ES(e){let n=0;if(KY.has(e.operator)&&(n=1),m(e))for(let t of e.ops)n+=ES(t);return n}function _S(e){if(I(e)||N(e))return 1;let n=1;if(m(e))for(let t of e.ops)n+=_S(t);return n}function x7(e){let n=ES(e),t=_S(e);return n*1e3+t}var v7=x7;function SS(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 Wp(e,n){let t=n(e);return t.isSame(e)?null:t}function E7(e,n){let t=Wp(e,bS),i=Wp(e,u7),r=[e];return t&&r.push(t),i&&r.push(i),SS(r,n)}function eW(e,n){return E7(e,n)}function nW(e,n){let t=Wp(e,l7),i=[e];if(t){i.push(t);let r=Wp(t,$b);r&&i.push(r)}return SS(i,n)}function tW(e,n){let t=Wp(e,$b),i=[e];return t&&i.push(t),SS(i,n)}function iW(e,n){let t=d7(e);return t=g7(t),t}function rW(e,n){let t=e;return t=f7(t),t=xS(t),t=bS(t),t=a7(t),t=xS(t),t=nW(t,n),t=E7(t,n),t=Lb(t),t=eW(t,n),t=Lb(t),t=tW(t,n),t}function _7(e,n){if(!Fb(e))return;let t=n?.measure??v7,i=n?.maxIterations??100,r=e,o=0,s=e,u=t(e),a=_=>{let w=t(_);w<u&&(s=_,u=w)};r=s7(r),a(r);let l=vS(r);a(l);let f=h7(r);a(f),r=s;let c=yS(r);if(a(c),r=s,Ys(r,"Sec","Csc")&&(r=i7(r),s=r,u=t(r)),Ys(r,"Tan","Cot")){let _=iW(r,t);a(_),r=_}if(Ys(r,"Tan","Cot")&&(r=r7(r),a(r)),Ys(r,"Sin","Cos")){let _=Lb(r);a(_),r=s}if(Ys(r,"Sin","Cos")){let _=t(r);for(;o<i;){o++;let w=rW(r,t),M=t(w);if(a(w),M>=_)break;r=w,_=M}}let p=o7(s);a(p);let d=c7(s);a(d);let g=p7(s);a(g);let h=b7(s);a(h);let b=yS(s);a(b);let y=vS(s);a(y);let x=$b(s);a(x);let v=y7(s);a(v);let S=m7(s);if(a(S),s.operator==="Add"||s.operator==="Multiply"){let _=e.engine.expr(s.json);a(_)}if(!s.isSame(e))return{value:s,because:"fu"}}function NS(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)NS(t,n);return}e!==null&&typeof e=="object"&&"fn"in e&&Array.isArray(e.fn)&&NS(e.fn,n)}var Qp=class e{static _latexSyntaxFactory=null;True;False;Pi;E;Nothing;Zero;One;Half;NegativeOne;Two;I;NaN;PositiveInfinity;NegativeInfinity;ComplexInfinity;_numericConfiguration;_cacheStore=new fb;_runtimeState=new Pb;_configurationLifecycle=new kb;_cost;_randomSeed=null;_rng;_integrationProvider;_simplificationRules=new tf([...r4]);_solveRules=new tf([...ok]);_harmonizationRules=new tf([...lk]);_compilationTargets=new Cb;_fuAlgorithm=_7;_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??=W6(this),this.__typeResolver}declareType(n,t,i){g4(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 nb(n)}constructor(n){if(n!==void 0&&typeof n!="object")throw Error("Unexpected argument");this.strict=!0,this._numericConfiguration=new Rb({precision:n?.precision,tolerance:n?.tolerance??"auto",angularUnit:"rad"});let t=new Db(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}),lN(this)}toJSON(){return"[ComputeEngine]"}[Symbol.toStringTag]="ComputeEngine";_reset(){this._configurationLifecycle.reset({refreshNumericConstants:()=>{},resetCommonSymbols:()=>Z4(this._commonSymbols),purgeCaches:()=>this._cacheStore.purgeValues()})}listenToConfigurationChange(n){return this._configurationLifecycle.listen(n)}_compile(n,t){return Op(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:Oc(J1(n))}_random(){return this._rng?this._rng():Math.random()}_randomNumericSeed(){return this._randomSeed===null?null:J1(this._randomSeed)}chop(n){let t=this._numericConfiguration.tolerance;return typeof n=="number"?Math.abs(n)<=t?0:n:n instanceof E?n.isPositive()&&n.lte(this._numericConfiguration.bignumTolerance)||n.isNegative()&&n.gte(this._numericConfiguration.negBignumTolerance)||n.isZero()?0:n:n instanceof F&&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 E&&(n=n.toNumber()),t instanceof E&&(t=t.toNumber()),new F(n,t)}_numericValue(n){if(n instanceof ze)return n.asExact??n;let t=this._numericConfiguration.precision>Ui?i=>new Iu(i):i=>new Mo(i);if(typeof n=="number")return Number.isInteger(n)?new Se(n,t):t(n);if(typeof n=="bigint")return new Se(n,t);if(vr(n))return new Se({rational:n},t);if(n instanceof E){if(n.isInteger()){let i=ln(n.toString());if(i!==null)return new Se(i,t)}return t(n)}if(n instanceof F)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 E&&n.re.isInteger()?new Se({rational:[ln(n.re.toString()),BigInt(1)]},t):typeof n.re=="number"&&Number.isInteger(n.re)?new Se({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:Sa(i.rational??[1,1])*Math.sqrt(i.radical)});if(i.radical>=ve){let[r,o]=Ai(i.radical,2);if(o>=ve)return t({re:Sa(i.rational??[1,1])*Math.sqrt(i.radical)});i={...i,radical:o,rational:Ge(i.rational??[1,1],[r,1])}}}return i.rational&&Yn(i.rational)&&(!Number.isInteger(i.rational[0])||!Number.isInteger(i.rational[1]))?t(i):new Se(i,t)}throw Error(`Unexpected value: ${typeof n=="object"?JSON.stringify(n):String(n)}`)}get costFunction(){return this._cost??vD}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 a4(this,n)}normalizeIdentifier(n){if(!n)return"";if(An(n))return n;this.pushScope();try{let t=this.parse(n);if(I(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 l4(this,n,t)}suggestOperatorName(n){return f4(this,n)}functionProperties(n){return ju(this,n)}_declareSymbolValue(n,t,i){return c4(this,n,t,i)}_declareSymbolOperator(n,t,i){return p4(this,n,t,i)}pushScope(n,t){y4(this,n,t)}popScope(){x4(this)}_pushEvalContext(n,t){l2(this,n,t)}_popEvalContext(){f2(this)}_inScope(n,t){return v4(this,n,t)}_printStack(n){E4(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 d4(this,n)}_setSymbolValue(n,t){m4(this,n,t)}declare(n,t,i){return h4(this,n,t,i)}declareSequence(n,t){return O4(this,n,t)}getSequenceStatus(n){return F4(this,n)}getSequence(n){return L4(this,n)}listSequences(){return $4(this)}isSequence(n){return B4(this,n)}clearSequenceCache(n){q4(this,n)}getSequenceCache(n){return V4(this,n)}getSequenceTerms(n,t,i,r){return j4(this,n,t,i,r)}lookupOEIS(n,t){return z4(this,n,t)}checkSequenceOEIS(n,t,i){return J4(this,n,t,i)}interpret(n,t){return G4(this,n,t)}assign(n,t){return b4(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}=rb(t);return Zt(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,...u}=t??{},a=u.diagnostics??this._latexOptions?.diagnostics??!1,l,f,c,p=new Set;if(a){l=[],c=g=>p.add(g);let d=new Set;f=g=>{let h=`${g.code} ${g.start} ${g.end} ${g.detail?JSON.stringify(g.detail):""}`;d.has(h)||(d.add(h),l.push(g))}}KE(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,...u,diagnostics:a,onDiagnostic:f,onBoundVariable:c});if(d===null)return null;let g=Zt(this,d,rb({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{e2(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&&NS(i,r),Array.from(r).sort()}function(n,t,i){let{canonical:r,structural:o}=rb(i);return ib(this,n,t,{metadata:i?.metadata,canonical:r,structural:o,scope:i?.scope})}error(n,t){return Ob(this,n,t)}typeError(n,t,i){return Q6(this,n,t,i)}hold(n){return this._fn("Hold",[this.expr(n,{form:"raw"})])}tuple(...n){return new En(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 Vs(this,n,t)}symbol(n,t){return U6(this,this._commonSymbols,n,t)}number(n,t){return Z6(this,this._commonNumbers,n,t)}rules(n,t){return Xc(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=Xc(this,this._simplificationRules.rules,{canonical:!0}).rules.filter(o=>o.purpose!=="expand");return{rules:OA(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",()=>Xc(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",()=>Xc(this,this._harmonizationRules.rules));return this._harmonizationRules.markCached(),t}}_fn(n,t,i){let r=i?.canonical??!0;return new En(this,n,t,{...i,canonical:r})}ask(n){return g2(this,n)}verify(n){return h2(this,n)}assume(n){return k4(this,n)}forget(n){b2(this,n)}};X6(()=>new Qp);var oW="0.86.1";return k7(sW);})();
|
|
1582
|
+
${i}`:i:n.preamble,o=new tS(t,r);return{target:"interval-js",success:!0,code:t,calling:"expression",run:o}}var Cb=class{_targets=new Map;register(n,t){DD(n),FD(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 Bp),this.register("glsl",new Vp),this.register("wgsl",new bb),this.register("python",new jp),this.register("interval-js",new Hp)}};var Ab=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 kb=class{_generation=0;_mutationGeneration=0;_ephemeralWriteDepth=0;_tracker=new Ab;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 xY(e){return!!(e===void 0||e==="Number"||e===!0||Array.isArray(e)&&e.includes("Number"))}function U6(e,n,t,i){let r=i?.canonical??!0,o=i?.metadata,s=t.normalize(),u=s.toLowerCase();if(u==="infinity"||u==="+infinity")return e.PositiveInfinity;if(u==="-infinity")return e.NegativeInfinity;if(e.strict&&!An(s))return e.error(["invalid-symbol",yi(s)],s);if(!r)return new fr(e,s,{metadata:o});if(e._isShadowedParameter(s)){let c=e._shadowedParameterType(s);if(c!==void 0){let d=e._shadowedParameterDef(s);if(d!==void 0)return new fr(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:c,inferred:!1},g);return e._setShadowedParameterDef(s,h),new fr(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 fr(e,s,{metadata:o,def:p})}let a=n[s];if(a)return a;let l=e.lookupDefinition(s);if(ie(l)&&l.value.holdUntil==="never")return l.value.value??e.Nothing;if(l)return new fr(e,s,{metadata:o,def:l});let f=e.context.lexicalScope;for(;f.noAutoDeclare&&f.parent;)f=f.parent;return l=e._declareSymbolValue(s,{type:"unknown",inferred:!0},f),new fr(e,s,{metadata:o,def:l})}function Z6(e,n,t,i){let r=i?.metadata;if(!xY(i?.canonical)&&vr(t))return e._fn("Rational",[e.number(t[0]),e.number(t[1])],{...r,canonical:!1});let s=Yg(e,t);if(r===void 0){if(typeof s=="number"){let u=s;if(u===1)return e.One;if(u===0)return e.Zero;if(u===-1)return e.NegativeOne;if(u===2)return e.Two;if(Number.isInteger(u)&&n[u]!==void 0)return n[u]??=new kn(e,s),n[u];if(Number.isNaN(u))return e.NaN;if(!Number.isFinite(u))return u<0?e.NegativeInfinity:e.PositiveInfinity}else if(s instanceof ze){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 kn(e,s,{metadata:r})}var tf=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 Rb=class{_precision;_angularUnit;_tolerance;_bignumTolerance;_negBignumTolerance;constructor(n){let t=n?.precision??p0;t==="machine"&&(t=Math.floor(Ui)),this._precision=t,E.precision=t,this._angularUnit=n?.angularUnit??"rad",this._tolerance=da,this._bignumTolerance=new E(da),this._negBignumTolerance=new E(-da),this.setTolerance(n?.tolerance??"auto")}get precision(){return this._precision}setPrecision(n){let t=n;if(t==="machine"&&(t=Ui),t==="auto"&&(t=p0),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,Ui),E.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=da),(!Number.isFinite(t)||t<0)&&(t=Math.pow(10,-this._precision+2)),this._tolerance=t,this._bignumTolerance=new E(t),this._negBignumTolerance=new E(-t)}get bignumTolerance(){return this._bignumTolerance}get negBignumTolerance(){return this._negBignumTolerance}get bignumNaN(){return E.NAN}get bignumZero(){return E.ZERO}get bignumOne(){return E.ONE}get bignumTwo(){return E.TWO}get bignumHalf(){return E.HALF}get bignumPi(){return E.PI}get bignumNegativeOne(){return E.NEGATIVE_ONE}bignum(n){if(n instanceof E)return n;try{return new E(n)}catch(t){t instanceof Error?console.error(t.message):console.error(String(t))}return E.NAN}};var Pb=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 Ce({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 vY(e){if(typeof e!="string")return LD(e),e;let n=Kh.find(t=>t.name===e);if(!n)throw new Error(`Unknown standard library: "${e}"`);return n}function H6(e){return e?eb(e.map(vY)):[...nb()]}function Y6(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)xD(e,o)}}function Yp(e,n){let t=e[n];if(!t)throw new Error(`Common symbol "${n}" failed to initialize`);return t}var Db=class{constructor(n){this.engine=n}engine;initializeCommonNumbers(){return{Zero:new kn(this.engine,0),One:new kn(this.engine,1),Half:new kn(this.engine,{rational:[1,2]}),NegativeOne:new kn(this.engine,-1),Two:new kn(this.engine,2),NaN:new kn(this.engine,Number.NaN),PositiveInfinity:new kn(this.engine,Number.POSITIVE_INFINITY),NegativeInfinity:new kn(this.engine,Number.NEGATIVE_INFINITY),I:new kn(this.engine,{im:1}),ComplexInfinity:new kn(this.engine,{re:1/0,im:1/0})}}bootstrapLibraries(n){let t=H6(n);Y6(this.engine,t)}initializeCommonSymbolBindings(n){return U4(this.engine,n),{True:Yp(n,"True"),False:Yp(n,"False"),Pi:Yp(n,"Pi"),E:Yp(n,"ExponentialE"),Nothing:Yp(n,"Nothing")}}};function EY(e){let n=[],t=e;for(;t;)t.types&&n.push(...Object.keys(t.types)),t=t.parent;return n}function _Y(e,n){let t=e;for(;t;){if(t.types?.[n])return t.types[n];t=t.parent}}function W6(e){return{get names(){return EY(e.context.lexicalScope)},resolve(n){return _Y(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 Ob(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&&$d(t)?r=e.function("LatexString",[e.string(ss(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 Q6(e,n,t,i){return t?Ob(e,["incompatible-type",le(n),t.toString()],i):Ob(e,["incompatible-type",le(n)],i)}var rS=null,oS=null;function X6(e){oS=e}function Hs(){if(!rS){if(!oS)throw new Error("ComputeEngine factory not registered. Import from the main module.");rS=oS()}return rS}function na(e,n){if(typeof e=="string"){let t=Hs();return t.parse(e,{strict:n?.strict??!1})??t.expr("Nothing")}return gd(e)?e:Hs().expr(e)}function sS(e,n){return Hs().expr(e,n)}function uS(e,n){return na(e,n).simplify(n)}function aS(e,n){return na(e,n).evaluate()}function lS(e,n){return na(e,n).N()}function fS(e,n){Hs().declare(e,n)}function cS(e,n){Hs().assign(e,n)}function pS(e,n){return Ae(na(e,n))}function dS(e,n,t){return na(e,t).solve(n)}function mS(e,n){return Ar(na(e,n))}function gS(e,n){return sr(na(e,n))}var SY=/^(Sin|Cos|Tan|Cot|Sec|Csc)$/;function Fb(e){return SY.test(e.operator)?!0:m(e)?e.ops.some(Fb):!1}function Ys(e,...n){return n.includes(e.operator)?!0:m(e)?e.ops.some(t=>Ys(t,...n)):!1}function wn(e,n){let t=e.engine;if(m(e)&&e.ops.length>0){let i=e,r=i.ops.map(s=>wn(s,n));r.some((s,u)=>s!==i.ops[u])&&(e=t._fn(i.operator,r))}return n(e)??e}function hS(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 NY(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 i7(e){return wn(e,NY)}function IY(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 r7(e){return wn(e,IY)}function wY(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"&&hS(t,i))return m(t)?n._fn("Tan",[t.op1]):void 0;if(t.operator==="Cos"&&i.operator==="Sin"&&hS(t,i))return m(t)?n._fn("Cot",[t.op1]):void 0}}function o7(e){return wn(e,wY)}function TY(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 MY(e){let n=e.engine,t=e.operator;if(!m(e))return;let i=e.op1;if(!i)return;let r=TY(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 s7(e){return wn(e,MY)}function CY(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 bS(e){return wn(e,CY)}function AY(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 u7(e){return wn(e,AY)}function kY(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 a7(e){return wn(e,kY)}function RY(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 K6(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 K6(n,o.ops)}}}if(m(e,"Add")&&e.ops.length===2){let i,r,o=!1,s=u=>u.re===-.5&&u.im===0;for(let u of e.ops){if(t(u)){i=u;continue}let a=u,l=!1;if(m(u,"Negate")&&(l=!0,a=u.op1),m(a,"Divide")&&a.op2?.isSame(2)){let f=a.op1;if(f?.operator==="Cos"){r=f,o=l;continue}}if(m(a,"Multiply")){let f=a.ops.findIndex(p=>t(p));if(f>=0){let p=a.ops.filter((d,g)=>g!==f);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=l;continue}}let c=a.ops.findIndex(p=>s(p));if(c>=0){let p=a.ops.filter((d,g)=>g!==c);if(p.length===1&&p[0].operator==="Cos"){r=p[0],o=!l;continue}}}}if(i&&r){if(!m(r))return;let u=r.op1;if(!u)return;let a;if(m(u,"Multiply")){let l=u.ops.findIndex(f=>f.isSame(2));if(l>=0){let f=u.ops.filter((c,p)=>p!==l);a=f.length===1?f[0]:n._fn("Multiply",f)}}return a?o?n._fn("Sin",[a]).pow(2):n._fn("Cos",[a]).pow(2):void 0}}}function K6(e,n){let t=-1,i=-1,r=!1;for(let a=0;a<n.length;a++)if(n[a].isSame(1))t=a;else if(n[a].operator==="Cos")i=a,r=!1;else if(n[a].operator==="Negate"){let l=n[a];m(l)&&l.op1?.operator==="Cos"&&(i=a,r=!0)}if(t<0||i<0)return;let o;if(r){let a=n[i];if(!m(a))return;o=a.op1}else o=n[i];if(!m(o))return;let s=o.op1;if(!s)return;let u;if(m(s,"Multiply")){let a=s.ops.findIndex(l=>l.isSame(2));if(a>=0){let l=s.ops.filter((f,c)=>c!==a);u=l.length===1?l[0]:e._fn("Multiply",l)}}if(u)return r?e._fn("Sin",[u]).pow(2):e._fn("Cos",[u]).pow(2)}function yS(e){return wn(e,RY)}function PY(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 u=o.op1,a=s.op1;if(!u||!a)continue;let l;if(o.operator==="Sin"&&s.operator==="Cos"?l=n._fn("Sin",[u.add(a)]).add(n._fn("Sin",[u.sub(a)])).div(2):o.operator==="Cos"&&s.operator==="Sin"?l=n._fn("Sin",[u.add(a)]).sub(n._fn("Sin",[u.sub(a)])).div(2):o.operator==="Cos"&&s.operator==="Cos"?l=n._fn("Cos",[u.add(a)]).add(n._fn("Cos",[u.sub(a)])).div(2):o.operator==="Sin"&&s.operator==="Sin"&&(l=n._fn("Cos",[u.sub(a)]).sub(n._fn("Cos",[u.add(a)])).div(2)),l){let f=t.filter((c,p)=>p!==i&&p!==r);return f.length===0?l:l.mul(f.length===1?f[0]:n._fn("Multiply",f))}}}function l7(e){return wn(e,PY)}function DY(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],u;if(o.operator==="Sin"&&s.operator==="Sin"){if(!m(o)||!m(s))continue;let a=o.op1,l=s.op1;if(a&&l){let f=a.add(l).div(2),c=a.sub(l).div(2);u=n._fn("Sin",[f]).mul(n._fn("Cos",[c])).mul(2)}}else if(o.operator==="Cos"&&s.operator==="Cos"){if(!m(o)||!m(s))continue;let a=o.op1,l=s.op1;if(a&&l){let f=a.add(l).div(2),c=a.sub(l).div(2);u=n._fn("Cos",[f]).mul(n._fn("Cos",[c])).mul(2)}}else if(o.operator==="Sin"&&s.operator==="Negate"){if(!m(o)||!m(s)||s.op1?.operator!=="Sin")continue;let a=s.op1;if(!m(a))continue;let l=o.op1,f=a.op1;if(l&&f){let c=l.add(f).div(2),p=l.sub(f).div(2);u=n._fn("Cos",[c]).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 a=s.op1;if(!m(a))continue;let l=o.op1,f=a.op1;if(l&&f){let c=l.add(f).div(2),p=l.sub(f).div(2);u=n._fn("Sin",[c]).mul(n._fn("Sin",[p])).mul(-2)}}if(u){let a=t.filter((l,f)=>f!==i&&f!==r);return a.length===0?u:u.add(a.length===1?a[0]:n._fn("Add",a))}}}function Lb(e){return wn(e,DY)}function OY(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 f7(e){return wn(e,OY)}function FY(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],u=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Sin"&&A.operator==="Cos"?{sin:M,cos:A}:M.operator==="Cos"&&A.operator==="Sin"?{sin:A,cos:M}:null},a=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Cos"&&A.operator==="Cos"?{cos1:M,cos2:A}:null},l=_=>{if(_.operator!=="Multiply"||!m(_))return null;let w=_.ops;if(w.length!==2)return null;let[M,A]=w;return M.operator==="Sin"&&A.operator==="Sin"?{sin1:M,sin2:A}:null},f=_=>m(_)?_.op1:void 0,c=u(o),p=u(s),d=m(o,"Negate")&&o.op1?u(o.op1):null,g=m(s,"Negate")&&s.op1?u(s.op1):null;if(c&&p){let _=f(c.sin),w=f(c.cos),M=f(p.sin),A=f(p.cos);if(_&&w&&M&&A&&_.isSame(A)&&w.isSame(M)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(c&&g){let _=f(c.sin),w=f(c.cos),M=f(g.sin),A=f(g.cos);if(_&&w&&M&&A&&_.isSame(A)&&w.isSame(M)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(d&&p){let _=f(d.sin),w=f(d.cos),M=f(p.sin),A=f(p.cos);if(_&&w&&M&&A&&M.isSame(w)&&A.isSame(_)){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Sin",[M.sub(A)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}let h=a(o),b=a(s),y=l(o),x=l(s),v=m(o,"Negate")&&o.op1?l(o.op1):null,S=m(s,"Negate")&&s.op1?l(s.op1):null;if(h&&S){let _=f(h.cos1),w=f(h.cos2),M=f(S.sin1),A=f(S.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(v&&b){let _=f(b.cos1),w=f(b.cos2),M=f(v.sin1),A=f(v.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.add(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(h&&x){let _=f(h.cos1),w=f(h.cos2),M=f(x.sin1),A=f(x.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}if(y&&b){let _=f(b.cos1),w=f(b.cos2),M=f(y.sin1),A=f(y.sin2);if(_&&w&&M&&A&&(_.isSame(M)&&w.isSame(A)||_.isSame(A)&&w.isSame(M))){let k=t.filter((q,O)=>O!==i&&O!==r),D=n._fn("Cos",[_.sub(w)]);return k.length===0?D:D.add(k.length===1?k[0]:n._fn("Add",k))}}}}function $b(e){return wn(e,FY)}function LY(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((a,l)=>l!==o),u=s.length===1?s[0]:n._fn("Multiply",s);return t==="Sin"?n._fn("Sin",[u]).mul(n._fn("Cos",[u])).mul(2):n._fn("Cos",[u]).pow(2).mul(2).sub(n.One)}}}function xS(e){return wn(e,LY)}function $Y(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((u,a)=>a!==i),o,s;for(let u of r)u.operator==="Sin"&&!o?o=u:u.operator==="Cos"&&!s&&(s=u);if(o&&s&&hS(o,s)){if(!m(o))return;let u=r.filter(l=>l!==o&&l!==s),a=n._fn("Sin",[o.op1.mul(2)]);return u.length===0?a:a.mul(u.length===1?u[0]:n._fn("Multiply",u))}}}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 a=t.op1,l=i.op1;if(m(a)&&m(l)){let f=l.op1;if(m(f)){let c=a.op1,p=f.op1;if(c&&p&&c.isSame(p))return n._fn("Cos",[c.mul(2)])}}}let r=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Cos"&&c.op2?.isSame(2)){let p=c.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=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Sin"&&c.op2?.isSame(2)){let p=c.op1;if(m(p))return p.op1}};if(t.isSame(1)&&m(i,"Negate")&&i.op1){let a=s(i.op1);if(a)return n._fn("Cos",[a.mul(2)])}if(i.isSame(1)&&m(t,"Negate")&&t.op1){let a=s(t.op1);if(a)return n._fn("Cos",[a.mul(2)])}let u=a=>{if(!m(a,"Multiply"))return;let l=a.ops.findIndex(p=>p.isSame(-2));if(l<0)return;let f=a.ops.filter((p,d)=>d!==l);if(f.length!==1)return;let c=f[0];if(m(c,"Power")&&c.op1?.operator==="Sin"&&c.op2?.isSame(2)){let p=c.op1;if(m(p))return p.op1}};if(t.isSame(1)){let a=u(i);if(a)return n._fn("Cos",[a.mul(2)])}if(i.isSame(1)){let a=u(t);if(a)return n._fn("Cos",[a.mul(2)])}}}function c7(e){return wn(e,$Y)}function e7(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(u=>u.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 BY(e){let n=e.engine;if(!m(e,"Add")||e.ops.length!==2)return;let t=e7(e.ops[0]),i=e7(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 p7(e){return wn(e,BY)}function qY(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 d7(e){return wn(e,qY)}var VY=[{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 jY(e,n=1e-10){for(let t of VY)if(Math.abs(t.value-e)<n)return t.angle}function zY(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 n7(e){if(m(e,"Multiply")){let n=!1,t;for(let i of e.ops)if(I(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(I(e,"Pi"))return[1,1]}function JY(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 v=t[x];if(m(v,"Tan")&&v.op1)i.push({arg:v.op1,index:x});else{let S=zY(v);S&&(r={coef:S[0],arg1:S[1],arg2:S[2],index:x})}}if(i.length!==2||!r)return;let[o,s]=i,u=o.arg.isSame(r.arg1)||o.arg.isSame(r.arg2),a=s.arg.isSame(r.arg1)||s.arg.isSame(r.arg2),l=o.arg.isSame(r.arg2)||o.arg.isSame(r.arg1),f=s.arg.isSame(r.arg2)||s.arg.isSame(r.arg1);if(!(u&&f||a&&l))return;let c=-r.coef;if(c<=0)return;let p=jY(c);if(!p)return;let d=n7(o.arg),g=n7(s.arg);if(!d||!g)return;let h=t7(t7(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 t7(e,n){return Math.abs(e*n)/GY(e,n)}function GY(e,n){for(e=Math.abs(e),n=Math.abs(n);n;){let t=n;n=e%n,e=t}return e}function m7(e){return wn(e,JY)}function UY(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 u=o.op1,a=s.op1;if(!(!u||!a)){if(o.operator==="Tan"&&s.operator==="Tan"){let l=o,f=s,c=n._fn("Cot",[u.add(a)]),p=n.One.sub(l.add(f).mul(c)),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,f=s,c=n._fn("Cot",[u.add(a)]),p=n.One.add(l.add(f).mul(c)),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 g7(e){return wn(e,UY)}function ZY(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 h7(e){return wn(e,ZY)}function HY(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,u=-1,a=!1;for(let p=0;p<t.length;p++){let d=t[p];d.isSame(1)?(s=p,a=!1):d.isSame(-1)||m(d,"Negate")&&d.op1?.isSame(1)?(s=p,a=!0):m(d,"Power")&&d.op2?.isSame(2)&&(u=p)}if(s<0||u<0)return;let l=t[u];if(!m(l))return;let f=l.op1;if(!f||!m(f))return;let c=f.op1;if(c){if(f.operator==="Sec"&&a)return n._fn("Tan",[c]).pow(2);if(f.operator==="Csc"&&a)return n._fn("Cot",[c]).pow(2);if(f.operator==="Tan"&&!a)return n._fn("Sec",[c]).pow(2);if(f.operator==="Cot"&&!a)return n._fn("Csc",[c]).pow(2)}}function vS(e){return wn(e,HY)}function YY(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((u,a)=>a!==t),s=o.length===1?o[0]:n._fn("Multiply",o);return[r,i,s]}}return[1,n.One,e]}function WY(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 M of t)if(m(M,"Cos")&&M.op1){let A=YY(M.op1);A?i.push({arg:A[2],numericMult:A[0],symbolicCoeff:A[1]}):i.push({arg:M.op1,numericMult:1,symbolicCoeff:n.One})}else r.push(M);if(i.length<2)return;let o=i[0].arg,s=i.filter(M=>M.arg.isSame(o)),u=i.filter(M=>!M.arg.isSame(o));if(s.length<2)return;s.sort((M,A)=>M.numericMult-A.numericMult);let a=[],l=[],f=[...s],c=f[0].numericMult;if(c>0){a.push(f[0]);let M=new Set([0]),A=c*2;for(;;){let k=f.findIndex((D,q)=>!M.has(q)&&Math.abs(D.numericMult-A)<1e-10);if(k===-1)break;a.push(f[k]),M.add(k),A*=2}l=f.filter((k,D)=>!M.has(D))}if(a.length<2)return;let p=a[0].numericMult,d=[...r];for(let M of l){let A=M.symbolicCoeff.isSame(n.One)?M.arg:n._fn("Multiply",[M.symbolicCoeff,M.arg]);d.push(n._fn("Cos",[A]))}for(let M of u){let A=M.symbolicCoeff.isSame(n.One)?M.arg:n._fn("Multiply",[M.symbolicCoeff,M.arg]);d.push(n._fn("Cos",[A]))}let g=a.length,h=a[0].symbolicCoeff,b=Math.pow(2,g);if(I(o,"Pi")){let M=1/(b+1);if(Math.abs(p-M)<1e-10){let A=n.number([1,b]);return d.length===0?A:A.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]),v=n._fn("Multiply",[y,o]),S=n._fn("Sin",[v]),_=n._fn("Sin",[x]),w=S.div(n.number(b).mul(_));return d.length===0?w:w.mul(d.length===1?d[0]:n._fn("Multiply",d))}function b7(e){return wn(e,WY)}function QY(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 XY(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 u=t[s],a=QY(u);a?i.push({...a,index:s}):typeof u.re=="number"&&u.im===0&&N(u)?o.push({value:u.re,index:s}):r.push({expr:u,index:s})}for(let s=0;s<i.length;s++)for(let u=s+1;u<i.length;u++){let a=i[s],l=i[u];if(a.arg.isSame(l.arg)&&(a.func==="Sin"&&l.func==="Cos"||a.func==="Cos"&&l.func==="Sin")&&Math.abs(a.coef-l.coef)<1e-10){let f=a.coef,c=new Set([a.index,l.index]),p=t.filter((d,g)=>!c.has(g));return p.length===0?n.number(f):f===1?n._fn("Add",[n.One,...p]):n._fn("Add",[n.number(f),...p])}}for(let s of i)if(s.coef<0){let u=Math.abs(s.coef);for(let a of o)if(Math.abs(a.value-u)<1e-10){let l=new Set([s.index,a.index]),f=t.filter((d,g)=>!l.has(g)),c=s.func==="Sin"?"Cos":"Sin",p=n._fn(c,[s.arg]).pow(2).mul(u);return f.length===0?p:n._fn("Add",[p,...f])}}}function y7(e){return wn(e,XY)}var KY=new Set(["Sin","Cos","Tan","Cot","Sec","Csc"]);function ES(e){let n=0;if(KY.has(e.operator)&&(n=1),m(e))for(let t of e.ops)n+=ES(t);return n}function _S(e){if(I(e)||N(e))return 1;let n=1;if(m(e))for(let t of e.ops)n+=_S(t);return n}function x7(e){let n=ES(e),t=_S(e);return n*1e3+t}var v7=x7;function SS(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 Wp(e,n){let t=n(e);return t.isSame(e)?null:t}function E7(e,n){let t=Wp(e,bS),i=Wp(e,u7),r=[e];return t&&r.push(t),i&&r.push(i),SS(r,n)}function eW(e,n){return E7(e,n)}function nW(e,n){let t=Wp(e,l7),i=[e];if(t){i.push(t);let r=Wp(t,$b);r&&i.push(r)}return SS(i,n)}function tW(e,n){let t=Wp(e,$b),i=[e];return t&&i.push(t),SS(i,n)}function iW(e,n){let t=d7(e);return t=g7(t),t}function rW(e,n){let t=e;return t=f7(t),t=xS(t),t=bS(t),t=a7(t),t=xS(t),t=nW(t,n),t=E7(t,n),t=Lb(t),t=eW(t,n),t=Lb(t),t=tW(t,n),t}function _7(e,n){if(!Fb(e))return;let t=n?.measure??v7,i=n?.maxIterations??100,r=e,o=0,s=e,u=t(e),a=_=>{let w=t(_);w<u&&(s=_,u=w)};r=s7(r),a(r);let l=vS(r);a(l);let f=h7(r);a(f),r=s;let c=yS(r);if(a(c),r=s,Ys(r,"Sec","Csc")&&(r=i7(r),s=r,u=t(r)),Ys(r,"Tan","Cot")){let _=iW(r,t);a(_),r=_}if(Ys(r,"Tan","Cot")&&(r=r7(r),a(r)),Ys(r,"Sin","Cos")){let _=Lb(r);a(_),r=s}if(Ys(r,"Sin","Cos")){let _=t(r);for(;o<i;){o++;let w=rW(r,t),M=t(w);if(a(w),M>=_)break;r=w,_=M}}let p=o7(s);a(p);let d=c7(s);a(d);let g=p7(s);a(g);let h=b7(s);a(h);let b=yS(s);a(b);let y=vS(s);a(y);let x=$b(s);a(x);let v=y7(s);a(v);let S=m7(s);if(a(S),s.operator==="Add"||s.operator==="Multiply"){let _=e.engine.expr(s.json);a(_)}if(!s.isSame(e))return{value:s,because:"fu"}}function NS(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)NS(t,n);return}e!==null&&typeof e=="object"&&"fn"in e&&Array.isArray(e.fn)&&NS(e.fn,n)}var Qp=class e{static _latexSyntaxFactory=null;True;False;Pi;E;Nothing;Zero;One;Half;NegativeOne;Two;I;NaN;PositiveInfinity;NegativeInfinity;ComplexInfinity;_numericConfiguration;_cacheStore=new fb;_runtimeState=new Pb;_configurationLifecycle=new kb;_cost;_randomSeed=null;_rng;_integrationProvider;_simplificationRules=new tf([...r4]);_solveRules=new tf([...ok]);_harmonizationRules=new tf([...lk]);_compilationTargets=new Cb;_fuAlgorithm=_7;_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??=W6(this),this.__typeResolver}declareType(n,t,i){g4(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 nb(n)}constructor(n){if(n!==void 0&&typeof n!="object")throw Error("Unexpected argument");this.strict=!0,this._numericConfiguration=new Rb({precision:n?.precision,tolerance:n?.tolerance??"auto",angularUnit:"rad"});let t=new Db(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}),lN(this)}toJSON(){return"[ComputeEngine]"}[Symbol.toStringTag]="ComputeEngine";_reset(){this._configurationLifecycle.reset({refreshNumericConstants:()=>{},resetCommonSymbols:()=>Z4(this._commonSymbols),purgeCaches:()=>this._cacheStore.purgeValues()})}listenToConfigurationChange(n){return this._configurationLifecycle.listen(n)}_compile(n,t){return Op(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:Oc(J1(n))}_random(){return this._rng?this._rng():Math.random()}_randomNumericSeed(){return this._randomSeed===null?null:J1(this._randomSeed)}chop(n){let t=this._numericConfiguration.tolerance;return typeof n=="number"?Math.abs(n)<=t?0:n:n instanceof E?n.isPositive()&&n.lte(this._numericConfiguration.bignumTolerance)||n.isNegative()&&n.gte(this._numericConfiguration.negBignumTolerance)||n.isZero()?0:n:n instanceof F&&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 E&&(n=n.toNumber()),t instanceof E&&(t=t.toNumber()),new F(n,t)}_numericValue(n){if(n instanceof ze)return n.asExact??n;let t=this._numericConfiguration.precision>Ui?i=>new Iu(i):i=>new Mo(i);if(typeof n=="number")return Number.isInteger(n)?new Se(n,t):t(n);if(typeof n=="bigint")return new Se(n,t);if(vr(n))return new Se({rational:n},t);if(n instanceof E){if(n.isInteger()){let i=ln(n.toString());if(i!==null)return new Se(i,t)}return t(n)}if(n instanceof F)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 E&&n.re.isInteger()?new Se({rational:[ln(n.re.toString()),BigInt(1)]},t):typeof n.re=="number"&&Number.isInteger(n.re)?new Se({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:Sa(i.rational??[1,1])*Math.sqrt(i.radical)});if(i.radical>=ve){let[r,o]=Ai(i.radical,2);if(o>=ve)return t({re:Sa(i.rational??[1,1])*Math.sqrt(i.radical)});i={...i,radical:o,rational:Ge(i.rational??[1,1],[r,1])}}}return i.rational&&Yn(i.rational)&&(!Number.isInteger(i.rational[0])||!Number.isInteger(i.rational[1]))?t(i):new Se(i,t)}throw Error(`Unexpected value: ${typeof n=="object"?JSON.stringify(n):String(n)}`)}get costFunction(){return this._cost??vD}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 a4(this,n)}normalizeIdentifier(n){if(!n)return"";if(An(n))return n;this.pushScope();try{let t=this.parse(n);if(I(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 l4(this,n,t)}suggestOperatorName(n){return f4(this,n)}functionProperties(n){return ju(this,n)}_declareSymbolValue(n,t,i){return c4(this,n,t,i)}_declareSymbolOperator(n,t,i){return p4(this,n,t,i)}pushScope(n,t){y4(this,n,t)}popScope(){x4(this)}_pushEvalContext(n,t){l2(this,n,t)}_popEvalContext(){f2(this)}_inScope(n,t){return v4(this,n,t)}_printStack(n){E4(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 d4(this,n)}_setSymbolValue(n,t){m4(this,n,t)}declare(n,t,i){return h4(this,n,t,i)}declareSequence(n,t){return O4(this,n,t)}getSequenceStatus(n){return F4(this,n)}getSequence(n){return L4(this,n)}listSequences(){return $4(this)}isSequence(n){return B4(this,n)}clearSequenceCache(n){q4(this,n)}getSequenceCache(n){return V4(this,n)}getSequenceTerms(n,t,i,r){return j4(this,n,t,i,r)}lookupOEIS(n,t){return z4(this,n,t)}checkSequenceOEIS(n,t,i){return J4(this,n,t,i)}interpret(n,t){return G4(this,n,t)}assign(n,t){return b4(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}=rb(t);return Zt(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,...u}=t??{},a=u.diagnostics??this._latexOptions?.diagnostics??!1,l,f,c,p=new Set;if(a){l=[],c=g=>p.add(g);let d=new Set;f=g=>{let h=`${g.code} ${g.start} ${g.end} ${g.detail?JSON.stringify(g.detail):""}`;d.has(h)||(d.add(h),l.push(g))}}KE(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,...u,diagnostics:a,onDiagnostic:f,onBoundVariable:c});if(d===null)return null;let g=Zt(this,d,rb({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{e2(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&&NS(i,r),Array.from(r).sort()}function(n,t,i){let{canonical:r,structural:o}=rb(i);return ib(this,n,t,{metadata:i?.metadata,canonical:r,structural:o,scope:i?.scope})}error(n,t){return Ob(this,n,t)}typeError(n,t,i){return Q6(this,n,t,i)}hold(n){return this._fn("Hold",[this.expr(n,{form:"raw"})])}tuple(...n){return new En(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 Vs(this,n,t)}symbol(n,t){return U6(this,this._commonSymbols,n,t)}number(n,t){return Z6(this,this._commonNumbers,n,t)}rules(n,t){return Xc(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=Xc(this,this._simplificationRules.rules,{canonical:!0}).rules.filter(o=>o.purpose!=="expand");return{rules:OA(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",()=>Xc(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",()=>Xc(this,this._harmonizationRules.rules));return this._harmonizationRules.markCached(),t}}_fn(n,t,i){let r=i?.canonical??!0;return new En(this,n,t,{...i,canonical:r})}ask(n){return g2(this,n)}verify(n){return h2(this,n)}assume(n){return k4(this,n)}forget(n){b2(this,n)}};X6(()=>new Qp);var oW="0.86.2";return k7(sW);})();
|
|
1583
1583
|
/*! Bundled license information:
|
|
1584
1584
|
|
|
1585
1585
|
complex-esm/dist/src/complex.js:
|