SPB Git

Repository Public MIT

API.md 12.6 KB 209 lines markdown

1<!--2ORIX Calc3File: Packages/ORIXGraph/API.md4Description: Public API of the graph computation engine, with usage snippets for the UI engineer.56Author: Simon-Pierre Boucher7Contact: contact@spboucher.ai8-->9# ORIXGraph — API1011Pure computation: expressions in, render-ready geometry out. No SwiftUI / UIKit / CoreGraphics. Everything public is `Sendable`;12every heavy function is synchronous, thread-safe and polls `Task.isCancelled`, so call it from a background task (or use the13`@concurrent` async wrappers of `GraphEngine`).1415All geometry is in **function coordinates**. Map to the screen with `Viewport.toScreen(_:)` (origin top-left, y down).1617```swift18import ORIXExpression   // EvalContext, Value, CalcError19import ORIXGraph20```2122## 1. From a text field to polylines2324```swift25// 1. The context holds the angle mode, the slider values and the user functions.26var context = EvalContext()27context.angleMode = .radians2829// 2. Parse once, when the text changes.30let item = try PlotParser.parse("a*sin(x)/x", context: context)      // throws CalcError / GraphError.notPlottable31item.kind         // .explicit(Expr)32item.parameters   // ["a"]  → create one slider per name33item.missingParameters(in: context)   // ["a"]: names that still need a value34context.variables["a"] = Value(2.0)   // slider value3536// 3. Describe the canvas.37let viewport = Viewport(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5, width: size.width, height: size.height)3839// 4. Geometry (off the main actor). Re-run on every viewport or slider change; compilation is included and cheap.40let g = try await GraphEngine.geometryAsync(for: item, viewport: viewport, context: context)4142// 5. Draw.43for line in g.polylines {                       // stroke each polyline separately — never join two of them44    var path = Path()45    path.addLines(line.points.map { let s = viewport.toScreen($0); return CGPoint(x: s.x, y: s.y) })46    if line.isClosed { path.closeSubpath() }47    canvas.stroke(path, with: .color(color), lineWidth: item.style.lineWidth)48}49for band in g.bands {                           // aliased region: fill, do not stroke a line through it50    canvas.fill(path(of: band.polygon), with: .color(color.opacity(0.35)))51}52for hole in g.holes { drawOpenCircle(at: viewport.toScreen(hole)) }          // removable discontinuities53for d in g.discontinuities where d.kind == .pole { drawDashedVertical(atX: viewport.screenX(d.x)) }   // optional asymptotes54for n in g.notices { show(n.message) }          // .aliased, .unreliable, .incomplete, .rejectedFalseContour, .info55```5657A polyline with a single point is an isolated point of the graph (for example `sign(0) = 0`): draw a dot.58Several items at once: `try await GraphEngine.geometries(for: items, viewport:context:)` → `[UUID: Result<PlotGeometry, CalcError>]`.5960### What `PlotParser.parse` understands6162| Text | `item.kind` |63|---|---|64| `sin(x)`, `y = x^2`, `x^2 = y`, `f(x) = x^2` (→ `item.definedFunction`) | `.explicit` (variable `x`) |65| `x = y^2`, `x = 3` | `.explicitX` (variable `y`) |66| `(cos(t), sin(2t))`, optional `for 0 <= t <= 2pi` or `{0 <= t <= 2pi}` | `.parametric` (variable `t`) |67| `r = 1 - cos(θ)`; angle written `θ`, `theta` or `t`; a bare expression in `θ` | `.polar` (variable `θ`) |68| `x^2 + y^2 = 25`, `sin(x) = cos(y)`, `xy = 1` | `.implicit(lhs:rhs:)` |69| `y < x^2`, `x^2 + y^2 <= 4`, `1 < x < 2`, `… and …`, `… or …` | `.inequality(condition:boundaries:)` |70| `(1, 2)`, `(1, 2), (3, 4)` | `.points(_, connected: false)` |71| `z = x*y`, `h(x, y) = …`, bare expression in `x` and `y` | `.surface` (use §4) |72| `a = 3` | `.parameter(name:value:)` (not drawable; set the slider) |73| `y = x^2 {-1 <= x <= 2}` | explicit with `item.domain` |7475Piecewise functions use the expression engine: `piecewise(x < 0, -x, x < 2, x^2)`, `if(x > 0, 1, -1)`.76`PlotParserOptions(splitUnknownIdentifiers:)` (default `true`) reads `ax` as `a·x`; names already in77`context.variables` / `context.functions` are never split. Data: `PlotItem.scatter(points)`, `PlotItem.series(points)`.78`PlotItem` carries `id`, `source`, `style` (`PlotStyle`: `colorIndex`, `lineWidth`, `dash`, `marker`, `fillOpacity` — pure data),79`isVisible`, `parameterRange` (t / θ; default 0…2π or one full turn in the current angle unit), `domain`.8081### `PlotGeometry`8283| Field | Meaning |84|---|---|85| `polylines: [Polyline]` | connected pieces (`points`, `isClosed`) |86| `bands: [EnvelopeBand]` | columns `(x0, x1, yMin, yMax)` where the function oscillates faster than the pixels; `polygon` is the outline to fill |87| `discontinuities: [Discontinuity]` | `kind` (`.pole`, `.jump`, `.removable`, `.undefinedInterval`, `.essential`), `x`, `xEnd`, `leftLimit`, `rightLimit` (`.finite(v)`, `.infinite(positive:)`, `.undefined`, `.none`), `openStart/openEnd` |88| `holes: [Point2]` | open-circle markers of removable discontinuities |89| `markers: [Point2]` | scatter points |90| `fill: RegionFill?` | inequality: `spans` = rectangles `(x0, x1, y0, y1)` to fill |91| `strictBoundary` | inequality with `<` / `>`: draw the boundary dashed |92| `transposed` | `x = g(y)`: in bands / discontinuities the independent variable is y |93| `notices`, `isComplete`, `evaluations` | honesty notices; `isComplete == false` after cancellation or budget exhaustion |9495### Lower-level samplers (closures instead of items)9697```swift98let f: RealFunction = { x in sin(x) / x }                       // return NaN where undefined99let plot = Sampler.sampleExplicit(f, viewport: viewport)        // ExplicitPlot: polylines, bands, discontinuities, holes, poles100let side = Sampler.sampleExplicitX(g, viewport: viewport)       // x = g(y)101let curve = Sampler.sampleParametric(x: fx, y: fy, range: 0...(2 * .pi), viewport: viewport)   // CurvePlot102let rose = Sampler.samplePolar(r, range: 0...(2 * .pi), radiansPerUnit: 1, viewport: viewport)103let implicit = ImplicitPlotter.plot({ x, y in x * x + y * y - 25 }, viewport: viewport)        // ImplicitPlot: polylines, reliable, reasons104let region = ImplicitPlotter.region({ x, y in y < x * x ? 1 : 0 }, viewport: viewport)        // RegionFill105```106107Options: `SamplerOptions` (`tolerance` 0.2 px, `maxDepth` 6, `verticalPadding` 1 viewport height, `detectAliasing`, `xRange`,108`clipMode` `.split` / `.clamp`, `maxEvaluations`), `CurveOptions` (`tolerance`, `initialSamples` 512, `maxDepth` 10, `padding`),109`ImplicitOptions` (`cellSize` 2 px, `coarseFactor` 4, `maxEvaluations`); grouped in `GraphOptions` for `GraphEngine`.110111## 2. Viewport, ticks, grid112113```swift114var v = Viewport(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5, width: 800, height: 600)   // always sanitised (inverted, NaN, zero span)115v = v.panned(byScreen: drag.width, drag.height)                 // content follows the finger116v = v.zoomed(by: magnification, aboutScreenPoint: Point2(pinch.x, pinch.y))   // > 1 zooms in, anchor stays put117v = v.equalAspect()                                             // circles look round118v = v.resized(width: w, height: h)119v = GraphEngine.autoFit(items, viewport: v, context: context)   // robust y-range (poles ignored); also v.autoFitY([f])120v.toScreen(p); v.toFunction(s); v.screenX(x); v.functionY(sy); v.unitsPerPixelX121122let grid = GridLines(viewport: v, xMode: .piMultiples)          // .decimal (1-2-5) or .piMultiples123for t in grid.x.major { drawLine(atX: v.screenX(t.value)); drawLabel(t.label) }   // ≤ 25 ticks, minimal-digit labels ("0.5", "2e12", "3π/4")124for x in grid.x.minor { drawFaintLine(atX: v.screenX(x)) }125let ticks = AxisTicks.make(min: 0, max: 30, pixelLength: 600, targetSpacing: 90)126```127128## 3. Analysis (function coordinates)129130`f` is a `RealFunction`; get it from an item with `try item.compiled(context: context).explicitFunction`.131132```swift133let range = viewport.xMin...viewport.xMax134GraphAnalysis.roots(of: f, in: range)                 // [PointOfInterest] — poles and jumps through zero are excluded135GraphAnalysis.extrema(of: f, in: range)               // .minimum / .maximum; no end points, plateaus, poles136GraphAnalysis.inflections(of: f, in: range)137GraphAnalysis.yIntercept(of: f)                       // nil when f(0) is undefined138GraphAnalysis.intersections(f, g, in: range)          // shared poles excluded139// PointOfInterest: kind, x, y, residual, report (VerificationReport: show a badge only if report.isVerified)140141let t = try GraphAnalysis.tangent(of: f, at: x0, scale: viewport.xSpan)     // slope, intercept, slopeError, report; throws .refused at corners / undefined points142let (p, q) = t.segment(in: viewport)143let d = GraphAnalysis.derivative(of: f, at: x0, scale: viewport.xSpan)      // NumericalEstimate (value, errorEstimate, converged)144let fPrime = GraphAnalysis.derivativeFunction(of: f, scale: viewport.xSpan) // RealFunction → Sampler.sampleExplicit(fPrime, …)145146let i = try GraphAnalysis.integral(of: f, from: a, to: b, viewport: viewport)   // throws GraphError.refused if a pole / undefined stretch is inside147i.value; i.errorEstimate; i.totalArea148for r in i.regions { fill(r.polygon, color: r.sign > 0 ? positive : negative) }  // split at the roots149let area = try GraphAnalysis.areaBetween(f, g, from: a, to: b, viewport: viewport)   // value = ∫(f − g), totalArea = ∫|f − g|, regions split at intersections150let length = try GraphAnalysis.arcLength(of: f, from: a, to: b).estimate.value151GraphAnalysis.discontinuities(of: f, in: a...b)152153// Trace cursor: compute the snap targets once per (function, viewport), then per drag event:154let targets = GraphAnalysis.pointsOfInterest(of: f, viewport: viewport)155let tp = GraphAnalysis.trace(f, screenX: location.x, viewport: viewport, pointsOfInterest: targets, snapRadius: 12)156tp.x; tp.y /* nil = undefined */; tp.screen; tp.snapped?.kind157158let rows = GraphAnalysis.table(of: f, start: -2, step: 0.5, count: 9)        // row.y == nil → row.text == "undefined"159```160161Errors: `GraphError.refused(message)` carries a sentence fit for display ("The function has a pole at x ≈ 0.0 inside the interval…").162163## 4. 3D surfaces164165```swift166guard case .surface(let f) = try item.compiled(context: context) else { return }167let mesh = SurfacePlotter.mesh(f, x: -3...3, y: -3...3, options: SurfaceOptions(columns: 60, rows: 60))168// mesh.vertices [(columns+1)·(rows+1) Point3, row-major], mesh.normals (unit, up), mesh.indices [UInt32] (3 per triangle, CCW from above),169// mesh.colorParameters (0…1 height for a colour ramp), mesh.valid, mesh.clipped, mesh.zMin/zMax (robust), mesh.droppedTriangles, mesh.notices170171let unit = mesh.normalized()                                    // vertices in [−1, 1]³, normals transformed172var camera = Camera3D(yaw: -.pi / 3, pitch: .pi / 6, distance: 4.5)173camera = camera.orbited(yawBy: dx * 0.01, pitchBy: dy * 0.01).zoomed(by: pinch)174175// Canvas fallback renderer (painter's algorithm): triangles sorted far → near, already projected176for t in PainterRenderer.project(unit, camera: camera, width: w, height: h) {177    canvas.fill(trianglePath(t.a, t.b, t.c), with: .color(ramp(t.colorParameter).scaled(by: t.shade)))178}179// Or with your own pipeline:180let m = camera.viewProjectionMatrix(aspect: w / h)               // 16 Doubles, column-major, OpenGL clip space181camera.project(Point3(0, 0, 1), width: w, height: h)             // Projection(screen:, depth:)?  (nil behind the camera)182PainterRenderer.depthOrder(unit, camera: camera)                 // triangle indices far → near183184SurfacePlotter.inspect(f, x: 1, y: 2, scale: 6)                  // z, gradient (∂f/∂x, ∂f/∂y), normal185let levels = SurfacePlotter.niceLevels(zMin: mesh.zMin, zMax: mesh.zMax)186let contours = SurfacePlotter.contours(f, levels: levels, x: -3...3, y: -3...3)   // [ContourLine(level, polylines, reliable)]187SurfacePlotter.parametricMesh({ u, v in Point3(cos(u) * sin(v), sin(u) * sin(v), cos(v)) }, u: 0...(2 * .pi), v: 0...(.pi))188```189190## 5. Data, fit overlay, export191192```swift193let item = PlotItem.scatter(points)                              // or .series(points) for a connected line194DataSeries.bounds(points); DataSeries.fit(points, viewport: v)   // window that shows all points195if let fit = DataSeries.linearFit(points) { fit.slope; fit.intercept; fit.rSquared; fit.segment(in: v) }196197CSVExport.curve(g.polylines)            // "x,y" at full double precision, blank line between polylines198CSVExport.curveWithSegments(g.polylines) // "segment,x,y"199CSVExport.table(rows)                    // undefined entries written as "undefined"200CSVExport.points(points)201```202203## 6. Cancellation and threading204205- Synchronous entry points check `Task.isCancelled` (once per pixel column / lattice row) and return what they have with206  `isComplete == false` and an `.incomplete` notice. Throwing analysis functions use `Task.checkCancellation()`.207- `GraphEngine.geometryAsync` / `geometries` are `@concurrent` (never on the main actor) and throw `CancellationError`.208- Typical pattern: keep one `Task` per item; cancel it and start a new one on each viewport / slider change.209
Files main
Menu

Theme