@nakafa/aksara-contracts 6.0.0 → 6.1.0

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.
Files changed (42) hide show
  1. package/dist/assessment/figure.d.ts +468 -0
  2. package/dist/math/bounds.d.ts +3 -2
  3. package/dist/math/bounds.js +37 -8
  4. package/dist/math/curve.d.ts +42 -0
  5. package/dist/math/curve.js +55 -0
  6. package/dist/math/formula/box.d.ts +61 -0
  7. package/dist/math/formula/box.js +68 -0
  8. package/dist/math/formula/compile.d.ts +11 -0
  9. package/dist/math/formula/compile.js +100 -0
  10. package/dist/math/formula/contour.d.ts +17 -0
  11. package/dist/math/formula/contour.js +162 -0
  12. package/dist/math/formula/field.d.ts +19 -0
  13. package/dist/math/formula/field.js +35 -0
  14. package/dist/math/formula/mesh.d.ts +25 -0
  15. package/dist/math/formula/mesh.js +28 -0
  16. package/dist/math/formula/names.d.ts +4 -0
  17. package/dist/math/formula/names.js +23 -0
  18. package/dist/math/formula/parse.d.ts +10 -0
  19. package/dist/math/formula/parse.js +240 -0
  20. package/dist/math/formula/plane.d.ts +62 -0
  21. package/dist/math/formula/plane.js +175 -0
  22. package/dist/math/formula/reader.d.ts +102 -0
  23. package/dist/math/formula/reader.js +58 -0
  24. package/dist/math/formula/sample.d.ts +14 -0
  25. package/dist/math/formula/sample.js +182 -0
  26. package/dist/math/formula/scope.d.ts +37 -0
  27. package/dist/math/formula/scope.js +137 -0
  28. package/dist/math/formula/space.d.ts +10 -0
  29. package/dist/math/formula/space.js +94 -0
  30. package/dist/math/formula/syntax.d.ts +77 -0
  31. package/dist/math/formula/syntax.js +111 -0
  32. package/dist/math/formula/token.d.ts +43 -0
  33. package/dist/math/formula/token.js +150 -0
  34. package/dist/math/plane.d.ts +85 -0
  35. package/dist/math/plane.js +8 -2
  36. package/dist/math/scene.js +11 -2
  37. package/dist/math/solid.d.ts +124 -0
  38. package/dist/math/solid.js +86 -0
  39. package/dist/math/space.d.ts +213 -0
  40. package/dist/math/space.js +8 -2
  41. package/dist/math/visual.d.ts +454 -0
  42. package/package.json +57 -1
@@ -0,0 +1,42 @@
1
+ import { Schema } from "effect";
2
+ /** The plane objects a formula defines, which a renderer samples itself. */
3
+ export declare const PlaneCurveObjectSchemas: readonly [Schema.Struct<{
4
+ readonly appearance: Schema.Literals<readonly ["answer", "construction", "highlight", "primary", "reference", "secondary", "warning"]>;
5
+ readonly id: Schema.String;
6
+ readonly domain: Schema.optionalKey<Schema.Struct<{
7
+ readonly max: Schema.Finite;
8
+ readonly min: Schema.Finite;
9
+ }>>;
10
+ readonly formula: Schema.String;
11
+ readonly inputAxis: Schema.optionalKey<Schema.Literals<readonly ["x", "y"]>>;
12
+ readonly kind: Schema.Literal<"function">;
13
+ }>, Schema.Struct<{
14
+ readonly appearance: Schema.Literals<readonly ["answer", "construction", "highlight", "primary", "reference", "secondary", "warning"]>;
15
+ readonly id: Schema.String;
16
+ readonly equation: Schema.String;
17
+ readonly kind: Schema.Literal<"implicit">;
18
+ }>, Schema.Struct<{
19
+ readonly appearance: Schema.Literals<readonly ["answer", "construction", "highlight", "primary", "reference", "secondary", "warning"]>;
20
+ readonly id: Schema.String;
21
+ readonly kind: Schema.Literal<"parametric">;
22
+ readonly parameter: Schema.Struct<{
23
+ readonly max: Schema.Finite;
24
+ readonly min: Schema.Finite;
25
+ }>;
26
+ readonly x: Schema.String;
27
+ readonly y: Schema.String;
28
+ }>, Schema.Struct<{
29
+ readonly appearance: Schema.Literals<readonly ["answer", "construction", "highlight", "primary", "reference", "secondary", "warning"]>;
30
+ readonly id: Schema.String;
31
+ readonly angle: Schema.Struct<{
32
+ readonly max: Schema.Finite;
33
+ readonly min: Schema.Finite;
34
+ }>;
35
+ readonly kind: Schema.Literal<"polar">;
36
+ readonly radius: Schema.String;
37
+ }>, Schema.Struct<{
38
+ readonly appearance: Schema.Literals<readonly ["answer", "construction", "highlight", "primary", "reference", "secondary", "warning"]>;
39
+ readonly id: Schema.String;
40
+ readonly inequalities: Schema.NonEmptyArray<Schema.String>;
41
+ readonly kind: Schema.Literal<"region">;
42
+ }>];
@@ -0,0 +1,55 @@
1
+ import { Schema } from "effect";
2
+ import { MathAxisRangeSchema } from "#contracts/math/base";
3
+ import { EquationTextSchema, FormulaTextSchema, InequalityTextSchema, } from "#contracts/math/formula/field";
4
+ import { MathObjectFields } from "#contracts/math/object";
5
+ /**
6
+ * The graph of y = f(x), or of x = f(y) when its input axis is y. The renderer
7
+ * samples it inside the frame, at least 200 times per visible branch, exactly
8
+ * at its domain ends and labels, and splits it at every break and asymptote.
9
+ * Without a domain it spans the frame along its input axis.
10
+ */
11
+ const PlaneFunctionObjectSchema = Schema.Struct({
12
+ ...MathObjectFields,
13
+ domain: Schema.optionalKey(MathAxisRangeSchema),
14
+ formula: FormulaTextSchema,
15
+ inputAxis: Schema.optionalKey(Schema.Literals(["x", "y"])),
16
+ kind: Schema.Literal("function"),
17
+ });
18
+ /** A curve traced by x(t) and y(t) while t runs over its parameter range. */
19
+ const PlaneParametricObjectSchema = Schema.Struct({
20
+ ...MathObjectFields,
21
+ kind: Schema.Literal("parametric"),
22
+ parameter: MathAxisRangeSchema,
23
+ x: FormulaTextSchema,
24
+ y: FormulaTextSchema,
25
+ });
26
+ /** A curve r = f(theta) in polar coordinates, theta in radians over its range. */
27
+ const PlanePolarObjectSchema = Schema.Struct({
28
+ ...MathObjectFields,
29
+ angle: MathAxisRangeSchema,
30
+ kind: Schema.Literal("polar"),
31
+ radius: FormulaTextSchema,
32
+ });
33
+ /** Every point of the frame where an equation in x and y holds, such as a conic. */
34
+ const PlaneImplicitObjectSchema = Schema.Struct({
35
+ ...MathObjectFields,
36
+ equation: EquationTextSchema,
37
+ kind: Schema.Literal("implicit"),
38
+ });
39
+ /**
40
+ * The part of the frame where every inequality holds, shaded, with each
41
+ * boundary drawn solid for <= or >= and dashed for < or >.
42
+ */
43
+ const PlaneRegionObjectSchema = Schema.Struct({
44
+ ...MathObjectFields,
45
+ inequalities: Schema.NonEmptyArray(InequalityTextSchema),
46
+ kind: Schema.Literal("region"),
47
+ });
48
+ /** The plane objects a formula defines, which a renderer samples itself. */
49
+ export const PlaneCurveObjectSchemas = [
50
+ PlaneFunctionObjectSchema,
51
+ PlaneImplicitObjectSchema,
52
+ PlaneParametricObjectSchema,
53
+ PlanePolarObjectSchema,
54
+ PlaneRegionObjectSchema,
55
+ ];
@@ -0,0 +1,61 @@
1
+ import { Schema } from "effect";
2
+ /** One sampled position; a plane curve keeps z at zero. */
3
+ export declare const SamplePointSchema: Schema.Struct<{
4
+ readonly x: Schema.Finite;
5
+ readonly y: Schema.Finite;
6
+ readonly z: Schema.Finite;
7
+ }>;
8
+ export type SamplePoint = typeof SamplePointSchema.Type;
9
+ /** One closed range of values, from its least to its greatest. */
10
+ export declare const SampleRangeSchema: Schema.Struct<{
11
+ readonly max: Schema.Finite;
12
+ readonly min: Schema.Finite;
13
+ }>;
14
+ export type SampleRange = typeof SampleRangeSchema.Type;
15
+ /** The frame a sampled curve is clipped to; a plane frame has no z range. */
16
+ export declare const SampleBoxSchema: Schema.Struct<{
17
+ readonly x: Schema.Struct<{
18
+ readonly max: Schema.Finite;
19
+ readonly min: Schema.Finite;
20
+ }>;
21
+ readonly y: Schema.Struct<{
22
+ readonly max: Schema.Finite;
23
+ readonly min: Schema.Finite;
24
+ }>;
25
+ readonly z: Schema.optionalKey<Schema.Struct<{
26
+ readonly max: Schema.Finite;
27
+ readonly min: Schema.Finite;
28
+ }>>;
29
+ }>;
30
+ export type SampleBox = typeof SampleBoxSchema.Type;
31
+ /** The three axes a sampled point has, in order. */
32
+ export declare const AXES: readonly ["x", "y", "z"];
33
+ /** Whether every coordinate of a point is finite. */
34
+ export declare function finite(point: SamplePoint): boolean;
35
+ /** The frame's ranges, with a plane frame's z pinned to zero. */
36
+ export declare function ranges(box: SampleBox): {
37
+ x: {
38
+ readonly max: number;
39
+ readonly min: number;
40
+ };
41
+ y: {
42
+ readonly max: number;
43
+ readonly min: number;
44
+ };
45
+ z: {
46
+ readonly max: number;
47
+ readonly min: number;
48
+ };
49
+ };
50
+ /** Distance between two points measured in frame spans, so every axis counts alike. */
51
+ export declare function spanDistance(box: SampleBox, from: SamplePoint, to: SamplePoint): number;
52
+ /** Whether a point lies inside the frame, its edges included. */
53
+ export declare function insideBox(box: SampleBox, point: SamplePoint): boolean;
54
+ /**
55
+ * Where a segment enters and leaves the frame, as fractions along it, or
56
+ * nothing when it misses the frame (Liang and Barsky's clipping).
57
+ */
58
+ export declare function clipSegment(box: SampleBox, from: SamplePoint, to: SamplePoint): {
59
+ enter: number;
60
+ leave: number;
61
+ } | undefined;
@@ -0,0 +1,68 @@
1
+ import { Array as Arr, Schema } from "effect";
2
+ /** One sampled position; a plane curve keeps z at zero. */
3
+ export const SamplePointSchema = Schema.Struct({
4
+ x: Schema.Finite,
5
+ y: Schema.Finite,
6
+ z: Schema.Finite,
7
+ });
8
+ /** One closed range of values, from its least to its greatest. */
9
+ export const SampleRangeSchema = Schema.Struct({
10
+ max: Schema.Finite,
11
+ min: Schema.Finite,
12
+ });
13
+ /** The frame a sampled curve is clipped to; a plane frame has no z range. */
14
+ export const SampleBoxSchema = Schema.Struct({
15
+ x: SampleRangeSchema,
16
+ y: SampleRangeSchema,
17
+ z: Schema.optionalKey(SampleRangeSchema),
18
+ });
19
+ /** The three axes a sampled point has, in order. */
20
+ export const AXES = ["x", "y", "z"];
21
+ /** Whether every coordinate of a point is finite. */
22
+ export function finite(point) {
23
+ return (Number.isFinite(point.x) &&
24
+ Number.isFinite(point.y) &&
25
+ Number.isFinite(point.z));
26
+ }
27
+ /** The frame's ranges, with a plane frame's z pinned to zero. */
28
+ export function ranges(box) {
29
+ return { x: box.x, y: box.y, z: box.z ?? { max: 0, min: 0 } };
30
+ }
31
+ /** Distance between two points measured in frame spans, so every axis counts alike. */
32
+ export function spanDistance(box, from, to) {
33
+ const all = ranges(box);
34
+ return Math.hypot(...Arr.map(AXES, (axis) => {
35
+ const span = all[axis].max - all[axis].min;
36
+ return span > 0 ? (to[axis] - from[axis]) / span : 0;
37
+ }));
38
+ }
39
+ /** Whether a point lies inside the frame, its edges included. */
40
+ export function insideBox(box, point) {
41
+ const all = ranges(box);
42
+ return (finite(point) &&
43
+ Arr.every(AXES, (axis) => point[axis] >= all[axis].min && point[axis] <= all[axis].max));
44
+ }
45
+ /**
46
+ * Where a segment enters and leaves the frame, as fractions along it, or
47
+ * nothing when it misses the frame (Liang and Barsky's clipping).
48
+ */
49
+ export function clipSegment(box, from, to) {
50
+ const all = ranges(box);
51
+ let enter = 0;
52
+ let leave = 1;
53
+ for (const axis of AXES) {
54
+ const delta = to[axis] - from[axis];
55
+ const { max, min } = all[axis];
56
+ if (delta === 0) {
57
+ if (from[axis] < min || from[axis] > max) {
58
+ return;
59
+ }
60
+ continue;
61
+ }
62
+ const first = (min - from[axis]) / delta;
63
+ const second = (max - from[axis]) / delta;
64
+ enter = Math.max(enter, Math.min(first, second));
65
+ leave = Math.min(leave, Math.max(first, second));
66
+ }
67
+ return enter <= leave ? { enter, leave } : undefined;
68
+ }
@@ -0,0 +1,11 @@
1
+ import { type FormulaNode } from "#contracts/math/formula/syntax";
2
+ /** The value of every variable and parameter a formula reads, by name. */
3
+ export type FormulaScope = Readonly<Record<string, number>>;
4
+ /** A compiled formula: its value for one scope, or NaN where it is undefined. */
5
+ export type FormulaEvaluator = (scope: FormulaScope) => number;
6
+ /**
7
+ * Compiles a parsed formula into a function of its variables. It never calls
8
+ * `eval` or `Function`: each node becomes a closure over its children, so a
9
+ * curve can be sampled thousands of times after one compile.
10
+ */
11
+ export declare function compileFormula(node: FormulaNode): FormulaEvaluator;
@@ -0,0 +1,100 @@
1
+ import { Array as Arr } from "effect";
2
+ import { FORMULA_CONSTANTS, } from "#contracts/math/formula/syntax";
3
+ /** Odd root indexes tried for a negative base, so `x^(1/3)` is real for x < 0. */
4
+ const ODD_ROOTS = [3, 5, 7, 9, 11];
5
+ const ROOT_TOLERANCE = 1e-9;
6
+ /**
7
+ * Raises a base to a power. A negative base with a fractional exponent whose
8
+ * denominator is odd, such as 1/3 or 2/5, has a real value, so it keeps one.
9
+ */
10
+ function power(base, exponent) {
11
+ const direct = base ** exponent;
12
+ if (!Number.isNaN(direct) || base >= 0) {
13
+ return direct;
14
+ }
15
+ for (const root of ODD_ROOTS) {
16
+ const numerator = exponent * root;
17
+ const whole = Math.round(numerator);
18
+ if (Math.abs(numerator - whole) < ROOT_TOLERANCE) {
19
+ return (whole % 2 === 0 ? 1 : -1) * Math.abs(base) ** exponent;
20
+ }
21
+ }
22
+ return Number.NaN;
23
+ }
24
+ /** How each operator combines its two values. */
25
+ const OPERATORS = {
26
+ "-": (left, right) => left - right,
27
+ "*": (left, right) => left * right,
28
+ "/": (left, right) => left / right,
29
+ "^": power,
30
+ "+": (left, right) => left + right,
31
+ };
32
+ /** What each function of one argument computes, in radians. */
33
+ const UNARY = {
34
+ abs: Math.abs,
35
+ acos: Math.acos,
36
+ asin: Math.asin,
37
+ atan: Math.atan,
38
+ cbrt: Math.cbrt,
39
+ ceil: Math.ceil,
40
+ cos: Math.cos,
41
+ cosh: Math.cosh,
42
+ cot: (value) => 1 / Math.tan(value),
43
+ csc: (value) => 1 / Math.sin(value),
44
+ exp: Math.exp,
45
+ floor: Math.floor,
46
+ ln: Math.log,
47
+ log: Math.log10,
48
+ sec: (value) => 1 / Math.cos(value),
49
+ sign: Math.sign,
50
+ sin: Math.sin,
51
+ sinh: Math.sinh,
52
+ sqrt: Math.sqrt,
53
+ tan: Math.tan,
54
+ tanh: Math.tanh,
55
+ };
56
+ /** Reads one name: a constant's value, or the scope's value for a variable. */
57
+ function compileName(name) {
58
+ if (name === "pi" || name === "e") {
59
+ const value = FORMULA_CONSTANTS[name];
60
+ return () => value;
61
+ }
62
+ return (scope) => scope[name] ?? Number.NaN;
63
+ }
64
+ /**
65
+ * Compiles a parsed formula into a function of its variables. It never calls
66
+ * `eval` or `Function`: each node becomes a closure over its children, so a
67
+ * curve can be sampled thousands of times after one compile.
68
+ */
69
+ export function compileFormula(node) {
70
+ if (node.kind === "number") {
71
+ const { value } = node;
72
+ return () => value;
73
+ }
74
+ if (node.kind === "name") {
75
+ return compileName(node.name);
76
+ }
77
+ if (node.kind === "negate") {
78
+ const operand = compileFormula(node.operand);
79
+ return (scope) => -operand(scope);
80
+ }
81
+ if (node.kind === "binary") {
82
+ const left = compileFormula(node.left);
83
+ const right = compileFormula(node.right);
84
+ const combine = OPERATORS[node.operator];
85
+ return (scope) => combine(left(scope), right(scope));
86
+ }
87
+ if (node.kind === "logarithm") {
88
+ const base = compileFormula(node.base);
89
+ const value = compileFormula(node.value);
90
+ return (scope) => Math.log(value(scope)) / Math.log(base(scope));
91
+ }
92
+ const [first, ...rest] = Arr.map(node.args, compileFormula);
93
+ const { callee } = node;
94
+ if (callee === "max" || callee === "min") {
95
+ const pick = callee === "max" ? Math.max : Math.min;
96
+ return (scope) => Arr.reduce(rest, first(scope), (value, each) => pick(value, each(scope)));
97
+ }
98
+ const apply = UNARY[callee];
99
+ return (scope) => apply(first(scope));
100
+ }
@@ -0,0 +1,17 @@
1
+ import { type SampleBox } from "#contracts/math/formula/box";
2
+ import type { SampleBranch } from "#contracts/math/formula/sample";
3
+ /** A field over the plane: its value at one point, NaN where it is undefined. */
4
+ export type SampleField = (x: number, y: number) => number;
5
+ /** Cells per frame side, enough for a smooth outline at the largest card size. */
6
+ export declare const CONTOUR_CELLS = 240;
7
+ /**
8
+ * Traces every curve where a field is zero inside the frame, the marching
9
+ * squares method, so an equation such as `x^2 + y^2 = 4` draws its circle.
10
+ */
11
+ export declare function contourLines(field: SampleField, box: SampleBox, cells?: number): readonly SampleBranch[];
12
+ /**
13
+ * Shades the part of the frame where a field is at least zero, one shape per
14
+ * cell: the corners inside and the crossings between them, so a cell wholly
15
+ * inside is its square and a cell the outline cuts keeps only its inner part.
16
+ */
17
+ export declare function contourFill(field: SampleField, box: SampleBox, cells?: number): readonly SampleBranch[];
@@ -0,0 +1,162 @@
1
+ import { Array as Arr, MutableHashMap, MutableHashSet, MutableList, Option, Result, Schema, } from "effect";
2
+ import { SamplePointSchema, } from "#contracts/math/formula/box";
3
+ /** Cells per frame side, enough for a smooth outline at the largest card size. */
4
+ export const CONTOUR_CELLS = 240;
5
+ /** One grid corner: its key, its point, and the field's value there when defined. */
6
+ const CornerSchema = Schema.Struct({
7
+ key: Schema.String,
8
+ point: SamplePointSchema,
9
+ value: Schema.Option(Schema.Finite),
10
+ });
11
+ /** One grid corner whose value is defined. */
12
+ const LocatedSchema = Schema.Struct({
13
+ key: Schema.String,
14
+ point: SamplePointSchema,
15
+ value: Schema.Finite,
16
+ });
17
+ /** One crossing on a cell edge: the shared key of that edge and its point. */
18
+ const CrossingSchema = Schema.Struct({
19
+ key: Schema.String,
20
+ point: SamplePointSchema,
21
+ });
22
+ /** One segment of an outline, with the order it was found in. */
23
+ const SegmentSchema = Schema.Struct({
24
+ from: CrossingSchema,
25
+ index: Schema.Int,
26
+ to: CrossingSchema,
27
+ });
28
+ /** Reads the field once at every corner of a square grid over the frame. */
29
+ function grid(field, box, cells) {
30
+ const dx = (box.x.max - box.x.min) / cells;
31
+ const dy = (box.y.max - box.y.min) / cells;
32
+ const columns = Arr.makeBy(cells + 1, (column) => Arr.makeBy(cells + 1, (row) => {
33
+ const x = box.x.min + column * dx;
34
+ const y = box.y.min + row * dy;
35
+ return {
36
+ key: `${column}:${row}`,
37
+ point: { x, y, z: 0 },
38
+ value: Option.liftPredicate(field(x, y), Number.isFinite),
39
+ };
40
+ }));
41
+ return Arr.flatMap(Arr.makeBy(cells, (column) => column), (column) => Arr.flatMap(Arr.makeBy(cells, (row) => row), (row) => Option.toArray(Option.all([
42
+ Arr.get(columns, column).pipe(Option.flatMap((each) => Arr.get(each, row))),
43
+ Arr.get(columns, column + 1).pipe(Option.flatMap((each) => Arr.get(each, row))),
44
+ Arr.get(columns, column + 1).pipe(Option.flatMap((each) => Arr.get(each, row + 1))),
45
+ Arr.get(columns, column).pipe(Option.flatMap((each) => Arr.get(each, row + 1))),
46
+ ]))));
47
+ }
48
+ /** One corner with its defined value, or nothing where the field is undefined. */
49
+ function locate(corner) {
50
+ return Option.map(corner.value, (value) => ({ key: corner.key, point: corner.point, value }));
51
+ }
52
+ /** The corners of a cell with their values, or nothing when any is undefined. */
53
+ function square([a, b, c, d]) {
54
+ return Option.all([locate(a), locate(b), locate(c), locate(d)]);
55
+ }
56
+ /** Whether a corner lies where the field is at least zero. */
57
+ function inside(corner) {
58
+ return corner.value >= 0;
59
+ }
60
+ /** Where the field crosses zero between two corners, if it does. */
61
+ function crossing(from, to) {
62
+ if (inside(from) === inside(to)) {
63
+ return Option.none();
64
+ }
65
+ const fraction = from.value / (from.value - to.value);
66
+ return Option.some({
67
+ key: from.key < to.key ? `${from.key}|${to.key}` : `${to.key}|${from.key}`,
68
+ point: {
69
+ x: from.point.x + (to.point.x - from.point.x) * fraction,
70
+ y: from.point.y + (to.point.y - from.point.y) * fraction,
71
+ z: 0,
72
+ },
73
+ });
74
+ }
75
+ /**
76
+ * The zero-crossing segments inside one cell. A saddle, where opposite
77
+ * corners agree, is resolved by the field's value at the cell center.
78
+ */
79
+ function cellSegments(field, cell) {
80
+ const [a, b, c, d] = cell;
81
+ const bottom = crossing(a, b);
82
+ const right = crossing(b, c);
83
+ const top = crossing(c, d);
84
+ const left = crossing(d, a);
85
+ return Option.match(Option.all([bottom, right, top, left]), {
86
+ onNone: () => Arr.getSomes(Arr.map([
87
+ [bottom, right],
88
+ [right, top],
89
+ [top, left],
90
+ [left, bottom],
91
+ [bottom, top],
92
+ [left, right],
93
+ ], ([from, to]) => Option.zipWith(from, to, (start, end) => [start, end]))),
94
+ onSome: ([down, east, up, west]) => {
95
+ const center = field((a.point.x + c.point.x) / 2, (a.point.y + c.point.y) / 2);
96
+ return center >= 0 === inside(a)
97
+ ? [[down, east], [up, west]]
98
+ : [[west, down], [east, up]];
99
+ },
100
+ });
101
+ }
102
+ /** Joins segments that share an edge crossing into continuous polylines. */
103
+ function join(segments) {
104
+ const byKey = MutableHashMap.empty();
105
+ Arr.forEach(segments, (segment) => {
106
+ for (const key of [segment.from.key, segment.to.key]) {
107
+ const known = Option.getOrElse(MutableHashMap.get(byKey, key), () => []);
108
+ MutableHashMap.set(byKey, key, [...known, segment]);
109
+ }
110
+ });
111
+ const used = MutableHashSet.empty();
112
+ return Arr.filterMap(segments, (start) => {
113
+ if (MutableHashSet.has(used, start.index)) {
114
+ return Result.failVoid;
115
+ }
116
+ MutableHashSet.add(used, start.index);
117
+ const line = MutableList.make();
118
+ MutableList.append(line, start.from.point);
119
+ MutableList.append(line, start.to.point);
120
+ let { key } = start.to;
121
+ let next = Option.none();
122
+ do {
123
+ next = Arr.findFirst(Arr.flatten(Option.toArray(MutableHashMap.get(byKey, key))), (segment) => !MutableHashSet.has(used, segment.index));
124
+ if (Option.isSome(next)) {
125
+ const segment = next.value;
126
+ MutableHashSet.add(used, segment.index);
127
+ const forward = segment.from.key === key;
128
+ MutableList.append(line, forward ? segment.to.point : segment.from.point);
129
+ key = forward ? segment.to.key : segment.from.key;
130
+ }
131
+ } while (Option.isSome(next));
132
+ return Result.succeed(MutableList.toArray(line));
133
+ });
134
+ }
135
+ /**
136
+ * Traces every curve where a field is zero inside the frame, the marching
137
+ * squares method, so an equation such as `x^2 + y^2 = 4` draws its circle.
138
+ */
139
+ export function contourLines(field, box, cells = CONTOUR_CELLS) {
140
+ const squares = Arr.getSomes(Arr.map(grid(field, box, cells), square));
141
+ const found = Arr.flatMap(squares, (cell) => cellSegments(field, cell));
142
+ return join(Arr.map(found, ([from, to], index) => ({ from, index, to })));
143
+ }
144
+ /**
145
+ * Shades the part of the frame where a field is at least zero, one shape per
146
+ * cell: the corners inside and the crossings between them, so a cell wholly
147
+ * inside is its square and a cell the outline cuts keeps only its inner part.
148
+ */
149
+ export function contourFill(field, box, cells = CONTOUR_CELLS) {
150
+ return Arr.filterMap(Arr.getSomes(Arr.map(grid(field, box, cells), square)), ([a, b, c, d]) => {
151
+ const outline = Arr.flatMap([
152
+ [a, b],
153
+ [b, c],
154
+ [c, d],
155
+ [d, a],
156
+ ], ([from, to]) => [
157
+ ...(inside(from) ? [from.point] : []),
158
+ ...Option.toArray(Option.map(crossing(from, to), ({ point }) => point)),
159
+ ]);
160
+ return outline.length >= 3 ? Result.succeed(outline) : Result.failVoid;
161
+ });
162
+ }
@@ -0,0 +1,19 @@
1
+ import { Schema } from "effect";
2
+ /** An authored expression, such as `2x^2 - 3x + 1` or `a sin(t)`. */
3
+ export declare const FormulaTextSchema: Schema.String;
4
+ /** An authored equation, such as `x^2 + y^2 = 4`. */
5
+ export declare const EquationTextSchema: Schema.String;
6
+ /** An authored inequality, such as `y < 2x + 1` or `x + y <= 4`. */
7
+ export declare const InequalityTextSchema: Schema.String;
8
+ /**
9
+ * One slider a learner moves to change every formula that reads its name. Its
10
+ * value starts inside its range, and a positive step, when given, snaps it.
11
+ */
12
+ export declare const FormulaParameterSchema: Schema.Struct<{
13
+ readonly max: Schema.Finite;
14
+ readonly min: Schema.Finite;
15
+ readonly name: Schema.String;
16
+ readonly step: Schema.optionalKey<Schema.Finite>;
17
+ readonly value: Schema.Finite;
18
+ }>;
19
+ export type FormulaParameter = typeof FormulaParameterSchema.Type;
@@ -0,0 +1,35 @@
1
+ import { Array as Arr, Result, Schema } from "effect";
2
+ import { readFormula, readRelation } from "#contracts/math/formula/parse";
3
+ import { FormulaParameterNameSchema, } from "#contracts/math/formula/syntax";
4
+ /** Passes a formula that reads, or names the problem of one that does not. */
5
+ function readable(read) {
6
+ return (text) => Result.match(read(text), {
7
+ onFailure: (problem) => problem.message,
8
+ onSuccess: () => true,
9
+ });
10
+ }
11
+ /** Passes a relation that reads with one of the allowed comparisons. */
12
+ function comparedWith(allowed, message) {
13
+ return (text) => Result.match(readRelation(text), {
14
+ onFailure: (problem) => problem.message,
15
+ onSuccess: ({ comparison }) => Arr.contains(allowed, comparison) || message,
16
+ });
17
+ }
18
+ /** An authored expression, such as `2x^2 - 3x + 1` or `a sin(t)`. */
19
+ export const FormulaTextSchema = Schema.String.check(Schema.makeFilter(readable(readFormula)));
20
+ /** An authored equation, such as `x^2 + y^2 = 4`. */
21
+ export const EquationTextSchema = Schema.String.check(Schema.makeFilter(comparedWith(["="], "Expected an equation with =.")));
22
+ /** An authored inequality, such as `y < 2x + 1` or `x + y <= 4`. */
23
+ export const InequalityTextSchema = Schema.String.check(Schema.makeFilter(comparedWith(["<", "<=", ">", ">="], "Expected <, <=, >, or >=.")));
24
+ /**
25
+ * One slider a learner moves to change every formula that reads its name. Its
26
+ * value starts inside its range, and a positive step, when given, snaps it.
27
+ */
28
+ export const FormulaParameterSchema = Schema.Struct({
29
+ max: Schema.Finite,
30
+ min: Schema.Finite,
31
+ name: FormulaParameterNameSchema,
32
+ step: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThan(0))),
33
+ value: Schema.Finite,
34
+ }).check(Schema.makeFilter(({ max, min, value }) => (min < max && min <= value && value <= max) ||
35
+ "Expected min < max and a value between them."));
@@ -0,0 +1,25 @@
1
+ import { Schema } from "effect";
2
+ import { type SamplePoint, type SampleRange } from "#contracts/math/formula/box";
3
+ /** Cells along each side of a sampled surface. */
4
+ export declare const MESH_CELLS = 96;
5
+ /**
6
+ * A surface sampled on a grid: (rows + 1) by (columns + 1) points, row by row,
7
+ * with nothing where the surface is undefined so a renderer leaves a hole.
8
+ */
9
+ export declare const SampleGridSchema: Schema.Struct<{
10
+ readonly columns: Schema.Int;
11
+ readonly points: Schema.$Array<Schema.Option<Schema.Struct<{
12
+ readonly x: Schema.Finite;
13
+ readonly y: Schema.Finite;
14
+ readonly z: Schema.Finite;
15
+ }>>>;
16
+ readonly rows: Schema.Int;
17
+ }>;
18
+ export type SampleGrid = typeof SampleGridSchema.Type;
19
+ /** Where a surface stands for one pair of parameter values. */
20
+ export type SampleSurface = (u: number, v: number) => SamplePoint;
21
+ /** Samples a surface over two parameter ranges on an even grid. */
22
+ export declare function sampleGrid(surface: SampleSurface, u: SampleRange, v: SampleRange, cells?: {
23
+ readonly columns: number;
24
+ readonly rows: number;
25
+ }): SampleGrid;
@@ -0,0 +1,28 @@
1
+ import { Array as Arr, Option, Schema } from "effect";
2
+ import { SamplePointSchema, } from "#contracts/math/formula/box";
3
+ /** Cells along each side of a sampled surface. */
4
+ export const MESH_CELLS = 96;
5
+ /**
6
+ * A surface sampled on a grid: (rows + 1) by (columns + 1) points, row by row,
7
+ * with nothing where the surface is undefined so a renderer leaves a hole.
8
+ */
9
+ export const SampleGridSchema = Schema.Struct({
10
+ columns: Schema.Int,
11
+ points: Schema.Array(Schema.Option(SamplePointSchema)),
12
+ rows: Schema.Int,
13
+ });
14
+ /** Samples a surface over two parameter ranges on an even grid. */
15
+ export function sampleGrid(surface, u, v, cells = {
16
+ columns: MESH_CELLS,
17
+ rows: MESH_CELLS,
18
+ }) {
19
+ const points = Arr.flatMap(Arr.makeBy(cells.rows + 1, (row) => row), (row) => Arr.makeBy(cells.columns + 1, (column) => {
20
+ const point = surface(u.min + ((u.max - u.min) * column) / cells.columns, v.min + ((v.max - v.min) * row) / cells.rows);
21
+ return Number.isFinite(point.x) &&
22
+ Number.isFinite(point.y) &&
23
+ Number.isFinite(point.z)
24
+ ? Option.some(point)
25
+ : Option.none();
26
+ }));
27
+ return { columns: cells.columns, points, rows: cells.rows };
28
+ }
@@ -0,0 +1,4 @@
1
+ import { HashSet } from "effect";
2
+ import { type FormulaNode } from "#contracts/math/formula/syntax";
3
+ /** Every variable and parameter a node reads; constants are left out. */
4
+ export declare function formulaNames(node: FormulaNode): HashSet.HashSet<string>;
@@ -0,0 +1,23 @@
1
+ import { Array as Arr, HashSet } from "effect";
2
+ import { FORMULA_CONSTANTS, } from "#contracts/math/formula/syntax";
3
+ /** Every variable and parameter a node reads; constants are left out. */
4
+ export function formulaNames(node) {
5
+ if (node.kind === "number") {
6
+ return HashSet.empty();
7
+ }
8
+ if (node.kind === "name") {
9
+ return node.name in FORMULA_CONSTANTS
10
+ ? HashSet.empty()
11
+ : HashSet.make(node.name);
12
+ }
13
+ if (node.kind === "negate") {
14
+ return formulaNames(node.operand);
15
+ }
16
+ if (node.kind === "binary") {
17
+ return HashSet.union(formulaNames(node.left), formulaNames(node.right));
18
+ }
19
+ if (node.kind === "logarithm") {
20
+ return HashSet.union(formulaNames(node.base), formulaNames(node.value));
21
+ }
22
+ return Arr.reduce(node.args, HashSet.empty(), (names, each) => HashSet.union(names, formulaNames(each)));
23
+ }