Repository Public MIT
1<!--2ORIX Calc3File: Packages/ORIXSymbolic/API.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# ORIXSymbolic — API reference89Symbolic layer of ORIX Calc. Depends on `ORIXExpression` (the `Expr` tree, parser, printer) and `ORIXNumerics`10(explanations, verification, root finding, quadrature). No UI, no global state: every function is a pure11`static func` on the `Symbolic` namespace and can be called from any thread.1213```swift14import ORIXExpression15import ORIXSymbolic1617let f = try Symbolic.parse("x^2 * sin(x)") // same as Parser.parse18```1920## The contract: every result says what it is2122```swift23public enum ResultKind { case exact, symbolic, numerical, unsupported, failedConvergence }24```2526| kind | meaning | what to show |27|---|---|---|28| `.exact` | exact value (number, or closed form in √, π, e, ln, i) | the expression, optionally the decimal reading |29| `.symbolic` | exact expression with free variables (derivative, antiderivative, simplified form) | the expression |30| `.numerical` | floating-point approximation from a numerical method | "≈ value", the error estimate, a "numerical" badge |31| `.unsupported` | outside the implemented rules, or refused (DEG mode, singularity, too large) | `note` |32| `.failedConvergence` | a numerical method ran and did not converge | `note` |3334A numerical value is **never** returned with kind `.exact`/`.symbolic`, and a numerical result never carries an `expression`.3536Most operations return a `SymbolicResult`:3738```swift39public struct SymbolicResult {40 var kind: ResultKind41 var expression: Expr? // nil when unsupported or purely numerical42 var values: [Value] // numerical value(s); the decimal reading of an exact constant43 var errorEstimate: Double? // numerical results44 var explanation: Explanation // ORIX Explain: the rules actually applied, in order45 var verification: VerificationReport // ORIX Verified Results: the checks actually run46 var note: String // why unsupported, assumptions, what a numerical value means47 var hasConstantOfIntegration: Bool48 var isSuccess: Bool // exact, symbolic or numerical49 var doubleValue: Double?50 var text: String // pretty text; appends " + C" for an indefinite integral51 func text(style: PrintStyle, constantOfIntegration: Bool = true) -> String // .pretty / .ascii / .latex52}53```5455Show `verification.isVerified` as the verified badge, `verification.warnings` as cautions, and56`explanation.steps` (label / expression / value) in the Explain panel. `explanation.assumptions` lists conventions57("Angles are in radians", "a ≠ 0", "|r| < 1").5859**Printing.** Use `result.text` or `Symbolic.string(expr, style:)` for expressions produced by this package. They are the same60as `Printer.string` but safe for deep trees (see the note at the end).6162**Options.**6364```swift65public struct SymbolicOptions { var angleMode: AngleMode = .radians; var assumePositive = false }66```6768* `angleMode`: symbolic calculus is done in radians. If you pass `.degrees` or `.gradians`, any operation whose input contains69 a trigonometric function returns `.unsupported` with a message asking for RAD. Expressions without trigonometry work in every70 mode. Recommended: run the Math screen in radians, or surface the message.71* `assumePositive` (Simplify only): treats every variable as a positive real, enabling √(x²) → x, ln(ab) → ln a + ln b,72 ln(xᵃ) → a·ln x, |x| → x.7374## Simplify tab7576```swift77Symbolic.simplify(P("(x^2-1)/(x-1) + sin(x)^2 + cos(x)^2")).text // "x + 2"78Symbolic.simplify(P("sqrt(x^2)")).text // "|x|"79Symbolic.simplify(P("sqrt(x^2)"), options: .init(assumePositive: true)).text // "x"80Symbolic.expand(P("(x+1)^3")).text // "x³ + 3x² + 3x + 1"81Symbolic.factor(P("2x^3+4x^2+2x")).text // "2x · (x + 1)²"82Symbolic.factor(P("x^2+1")).note // "The polynomial is irreducible over the rationals."83```8485`factor(_:variable:)` handles one-variable polynomials with rational coefficients; anything else is `.unsupported`.86`Polynomial` is public for direct use:8788```swift89let p = Polynomial(P("x^3 - 6x^2 + 11x - 6"), variable: "x")! // nil when not a rational polynomial90p.degree; p.coefficients // ascending BigRational coefficients91let (q, r) = p.dividing(by: Polynomial(integers: [-1, 1])) // p = q·(x − 1) + r92Polynomial.gcd(p, q); p.derivative; p.evaluate(BigRational(1, 2)); p.composed(with: q)93p.factorized() // Factorization: content, [PolynomialFactor(polynomial, multiplicity, isProvenIrreducible)]94Symbolic.polynomialRoots(p) // PolynomialRootsResult: roots (expression?, real, imaginary, multiplicity, kind, residual)95```9697## Derivative tab9899```swift100let d = Symbolic.differentiate(P("x^2*sin(x)"), variable: "x") // order: 1 by default101d.text // "x² · cos(x) + 2x · sin(x)"102d.explanation.plainText // Product rule … u = x², v = sin(x) …103Symbolic.differentiate(P("x^5"), variable: "x", order: 3) // 60x²104Symbolic.differentiate(P("x^2*y^3"), variables: ["x", "y"]) // ∂²/∂x∂y → 6x·y²105Symbolic.gradient(P("x^2*y + sin(y)"), variables: ["x", "y"]).text // "[2x · y, x² + cos(y)]"106```107108The verification compares the symbolic derivative with a numerical (Ridders) derivative at sample points.109Unsupported: `gamma`, factorial, `min`/`max`, `if`/`piecewise`, comparisons, vectors. `|x|′ = sign(x)` is returned with the110assumption "not differentiable at 0".111112## Integral tab113114```swift115let i = Symbolic.integrate(P("x*e^x"), variable: "x") // indefinite116i.text // "x · exp(x) − exp(x) + C" (the Expr has no "+ C")117i.verification // "Differentiate the antiderivative": passed118Symbolic.integrate(P("e^(-x^2)"), variable: "x").kind // .unsupported, note: "No closed form found…"119120let a = Symbolic.integrate(P("sin(x)"), variable: "x", from: P("0"), to: P("pi")) // .exact, "2"121let n = Symbolic.integrate(P("e^(-x^2)"), variable: "x", from: P("0"), to: P("1")) // .numerical122n.doubleValue; n.errorEstimate // 0.746824132812…, ~1e-12123Symbolic.integrate(P("1/x"), variable: "x", from: P("-1"), to: P("1")).kind // .unsupported (singularity at 0)124Symbolic.integrate(P("1/(1+x^2)"), variable: "x", from: P("-inf"), to: P("inf")).text // "π"125```126127Bounds are expressions (`inf`, `-inf`, `pi/2`, …). Definite-integral outcomes:128exact value (antiderivative found, no discontinuity detected, cross-checked by quadrature) · `.numerical` with129`errorEstimate` (no antiderivative, or piecewise integrand) · `.unsupported` (singularity inside the interval, integrand not130real on part of it) · `.failedConvergence` · `.exact` with expression `inf`/`−inf` and a "diverges" note · `.symbolic` with a131warning when bounds or integrand contain parameters.132133## Limit tab134135```swift136let l = Symbolic.limit(P("sin(x)/x"), variable: "x", to: .zero) // direction: .both (default), .left, .right137l.kind; l.behavior; l.text // .exact, .finite, "1"138Symbolic.limit(P("(1+1/x)^x"), variable: "x", to: P("inf")).text // "e"139let none = Symbolic.limit(P("1/x"), variable: "x", to: .zero)140none.behavior; none.leftText; none.rightText // .doesNotExist, "−∞", "∞"141Symbolic.limit(P("sqrt(x^2+x)-x"), variable: "x", to: P("inf")) // .numerical, value 0.5, errorEstimate142```143144`LimitResult`: `kind`, `behavior` (`.finite`, `.positiveInfinity`, `.negativeInfinity`, `.doesNotExist`, `.undetermined`),145`expression` (exact value, or `inf` / `−inf`), `value`, `errorEstimate`, `leftText`, `rightText`, `explanation`, `verification`,146`note`, `text`.147148## Series tab149150```swift151let s = Symbolic.taylor(P("sin(x)"), variable: "x", around: .zero, order: 5)152s.text // "x − x³/6 + x⁵/120 + O(x⁶)"153s.expression // the polynomial only154s.coefficients // [Expr] c₀…c₅ ; s.order == 5 ; s.remainder == "O(x⁶)"155156Symbolic.sum(P("k^2"), index: "k", from: P("1"), to: P("n")).text // "n · (2n + 1) · (n + 1)/6"157Symbolic.sum(P("(1/2)^k"), index: "k", from: P("0"), to: P("inf")).text // "2" (note: convergent, |r| < 1)158Symbolic.sum(P("1/k"), index: "k", from: P("1"), to: P("4")).text // "25/12"159```160161## Solve tab162163```swift164let r = Symbolic.solve(P("x^2 - 5x + 6 = 0"), for: "x") // an expression without "=" is read as "= 0"165r.kind // .exact166r.solutions.map(\.text) // ["2", "3"]167r.explanation.plainText // Quadratic formula … Δ = 1 …168Symbolic.solve(P("x^2+1=0"), for: "x").solutions.map(\.text) // ["−i", "i"]; realSolutions is empty169Symbolic.solve(P("sqrt(x+1)=x-1"), for: "x").rejected // ["x = 0: extraneous, residual 2.0e+00"]170Symbolic.solve(P("cos(x)=x"), for: "x", in: -10...10) // .numerical, roots in the interval only171```172173`SolveResult`: `kind`, `solutions: [Solution]` (real ones first, increasing), `realSolutions`, `rejected`, `isIdentity`,174`explanation`, `verification`, `note`. `Solution`: `expression?`, `real`, `imaginary`, `isReal`, `multiplicity`, `kind`,175`residual`, `text`. For trigonometric equations the principal solutions are returned and `note` gives the general solution.176The `in:` interval is used only by the numerical fallback (default [−10, 10]).177178## System tab179180```swift181let s = Symbolic.solveLinearSystem([P("2x+y=5"), P("x-y=1")], variables: ["x", "y"])182s.classification // .unique / .none / .infinitelyMany183s.solution // ["x": 2, "y": 1] as Expr; parametric in s.freeVariables when infinitely many184s.values; s.rank185186let n = Symbolic.solveSystem([P("x^2+y^2=4"), P("x*y=1")], variables: ["x", "y"],187 guesses: [[1, 1]], searchBox: -10...10)188n.kind // .numerical (or .exact when the system is linear: see n.linear)189n.solutions // [SystemSolution(values, residual, iterations)]190```191192## ODE tab193194```swift195let o = Symbolic.solveODE([P("-2y")], states: ["y"], independent: "t", initial: [1], from: 0, to: 3,196 method: .dormandPrince(relativeTolerance: 1e-8, absoluteTolerance: 1e-10)) // or .rk4(steps: 1000)197o.kind // .numerical, or .failedConvergence (blow-up / stiffness) with the partial trajectory198o.times; o.values // trajectory: values[k] is the state vector at times[k]199o.finalState; o.finalErrorEstimate; o.statistics // accepted / rejected steps, evaluations, smallest / largest step200o.value(of: "y", at: 1.5) // linear interpolation for plotting201202Symbolic.solveSecondOrderODE(P("-y"), state: "y", derivative: "v", initialValue: 1, initialDerivative: 0, from: 0, to: 10)203```204205## Optimize tab206207```swift208let m = Symbolic.optimize(P("x^3-3x"), variable: "x", from: P("-3"), to: P("3"))209m.criticalPoints // [CriticalPoint]: location?, x, valueExpression?, value, classification, secondDerivative, kind210m.endpoints; m.globalMinimum; m.globalMaximum // global extrema include the endpoints211m.kind // .exact when every critical point has a closed form, else .numerical212213let z = Symbolic.minimize(P("(1-x)^2+100(y-x^2)^2"), variables: ["x", "y"], start: [-1.2, 1]) // also maximize(…)214z.point; z.value; z.gradientNorm; z.kind // always .numerical: a local minimum from the starting point215```216217## Notes for integration218219* **Threading / stack.** Expression trees are processed recursively (also by `Printer` and `CompiledExpression`). Each public220 function runs its work synchronously on a dedicated thread with a 64 MB stack, so it is safe to call from a Swift221 concurrency task or a GCD queue. Calls are blocking; run them off the main actor for long problems.222* **Bounds.** Inputs above 20 000 nodes or nesting depth 400 are refused (`.unsupported`, "too large"). All searches have223 explicit caps (integration rule budget, L'Hôpital count, derivative size, Kronecker candidates, ODE steps).224* **Printing deep results.** Calling `Printer.string` directly from a secondary thread on a result with a long sum can225 overflow that thread's stack; use `result.text` / `Symbolic.string`.226* **Special names.** `inf` is infinity, `i` the imaginary unit, `e` and `pi` the constants; `log(x)` is base 10, `ln(x)` natural.227