@algorisys/tinyfly 0.118.0 → 0.120.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.
@@ -84,6 +84,8 @@ export interface TexPlacement {
84
84
  opacity?: number;
85
85
  /** Prefixed to every piece's id, so several equations in one figure stay apart */
86
86
  idPrefix: string;
87
+ /** Colour names TeX's \\color{…} may use (a theme's palette), mapped to CSS colours */
88
+ palette?: Record<string, string>;
87
89
  }
88
90
  /** The origin (left edge, baseline) of a layout placed by `place`, in px. */
89
91
  export declare function texOrigin(layout: TexLayout, place: Pick<TexPlacement, 'x' | 'y' | 'size' | 'align' | 'baseline'>): Vec2;
@@ -1,5 +1,7 @@
1
1
  import type { Vec2 } from '../linear/vec2';
2
2
  import type { SearchKind } from '../discrete/graph-search';
3
+ import type { Activation } from '../ml/network';
4
+ import type { Colormap } from '../ml/colormap';
3
5
  /**
4
6
  * A maths figure as plain JSON: a coordinate plane and the items drawn on it.
5
7
  *
@@ -395,7 +397,105 @@ export interface ClockItem extends ItemBase {
395
397
  /** World units (default 2) */
396
398
  radius?: number;
397
399
  }
398
- export type MathItem = GridItem | AxesItem | VectorItem | BasisItem | PointItem | FunctionItem | ParametricItem | PolygonItem | LineItem | LabelItem | EquationItem | TangentItem | RiemannItem | AreaItem | TaylorItem | HistogramItem | DistributionItem | GaltonItem | ScatterItem | BayesItem | GraphItem | VennItem | ClockItem;
400
+ /** A fully connected neural network; activations flow layer by layer as `flow` grows. */
401
+ export interface NetworkItem extends ItemBase {
402
+ kind: 'network';
403
+ /** Nodes per layer, input first: [3, 4, 4, 2] */
404
+ layers: number[];
405
+ /** Seed for the weights (default the item id) */
406
+ seed?: number | string;
407
+ activation?: Activation;
408
+ /** Input values (numbers or value names; default 0.5 each) */
409
+ inputs?: NumRef[];
410
+ /** How far activations have flowed: 0 the inputs only, 1 the first hidden layer … (default all) */
411
+ flow?: NumRef;
412
+ /** Centre and size, world units (default most of the view) */
413
+ at?: Vec2;
414
+ size?: Vec2;
415
+ /** TeX labels beside the input and output nodes */
416
+ labels?: {
417
+ inputs?: string[];
418
+ outputs?: string[];
419
+ };
420
+ /** Node radius, px at a 600 px figure (default 16) */
421
+ radius?: number;
422
+ }
423
+ /** A grid of coloured cells: given values (attention weights) or a function of x and y. */
424
+ export interface HeatmapItem extends ItemBase {
425
+ kind: 'heatmap';
426
+ /** Rows of values, top row first */
427
+ cells?: number[][];
428
+ /** Or a function of x and y, sampled over `region` */
429
+ expr?: string;
430
+ region?: [[number, number], [number, number]];
431
+ /** Samples per side for `expr` (default 48) */
432
+ resolution?: number;
433
+ /** Normalise each row with softmax first, as attention does */
434
+ softmax?: boolean;
435
+ /** World bottom-left corner and size, for `cells` (default most of the view) */
436
+ at?: Vec2;
437
+ size?: Vec2;
438
+ /** Value range for the colours (default the cells' min and max) */
439
+ range?: [number, number];
440
+ colormap?: Colormap;
441
+ rowLabels?: string[];
442
+ colLabels?: string[];
443
+ /** Write each value in its cell (default false) */
444
+ values?: boolean;
445
+ }
446
+ /** Level curves of f(x, y). */
447
+ export interface ContoursItem extends ItemBase {
448
+ kind: 'contours';
449
+ expr: string;
450
+ /** How many levels between the sampled min and max (default 10), or the levels themselves */
451
+ levels?: number | number[];
452
+ region?: [[number, number], [number, number]];
453
+ resolution?: number;
454
+ colormap?: Colormap;
455
+ width?: number;
456
+ }
457
+ /** Gradient descent on f(x, y) from `start`: `steps` taken so far (fractional: the next one under way). */
458
+ export interface DescentItem extends ItemBase {
459
+ kind: 'descent';
460
+ expr: string;
461
+ start: VecRef;
462
+ rate: NumRef;
463
+ steps: NumRef;
464
+ momentum?: NumRef;
465
+ width?: number;
466
+ }
467
+ /** Logistic regression on two seeded clusters, trained epoch by epoch: the decision boundary moves into place. */
468
+ export interface ClassifierItem extends ItemBase {
469
+ kind: 'classifier';
470
+ /** Cluster centres (default [[-1.5, -1], [1.5, 1]]) */
471
+ centres?: [Vec2, Vec2];
472
+ /** Points per cluster (default 40) */
473
+ count?: number;
474
+ spread?: number;
475
+ seed?: number | string;
476
+ /** Epochs trained (fractional: part way to the next) */
477
+ epochs: NumRef;
478
+ /** Learning rate (default 0.5) */
479
+ rate?: number;
480
+ /** The model before training, [w₁, w₂, b] (default a deliberately wrong guess, so the boundary visibly turns into place) */
481
+ start?: [number, number, number];
482
+ /** Shade P(class) behind the points (default true) */
483
+ probability?: boolean;
484
+ }
485
+ /** k-means on seeded clusters: points coloured by their nearest centroid, centroids moving each iteration. */
486
+ export interface KMeansItem extends ItemBase {
487
+ kind: 'kmeans';
488
+ /** Where the true clusters are */
489
+ centres: Vec2[];
490
+ count?: number;
491
+ spread?: number;
492
+ seed?: number | string;
493
+ /** How many centroids (default one per centre) */
494
+ k?: number;
495
+ /** Iterations done (fractional: centroids part way to the next) */
496
+ iteration: NumRef;
497
+ }
498
+ export type MathItem = GridItem | AxesItem | VectorItem | BasisItem | PointItem | FunctionItem | ParametricItem | PolygonItem | LineItem | LabelItem | EquationItem | TangentItem | RiemannItem | AreaItem | TaylorItem | HistogramItem | DistributionItem | GaltonItem | ScatterItem | BayesItem | GraphItem | VennItem | ClockItem | NetworkItem | HeatmapItem | ContoursItem | DescentItem | ClassifierItem | KMeansItem;
399
499
  export type MathItemKind = MathItem['kind'];
400
500
  export declare const ITEM_KINDS: readonly MathItemKind[];
401
501
  export type MathThemeName = 'dark' | 'light' | 'chalk';
@@ -0,0 +1,47 @@
1
+ import { type LogisticModel } from '../../ml/classify';
2
+ import { type Vec2 } from '../../linear/vec2';
3
+ import type { ClassifierItem, ContoursItem, DescentItem, HeatmapItem, KMeansItem, NetworkItem } from '../figure-spec';
4
+ import { type Shape } from '../display-list';
5
+ import { type ItemContext, type Values } from '../item-context';
6
+ /** Every layer's activations, and how far they have flowed. */
7
+ export declare function networkState(item: NetworkItem, values: Values): {
8
+ network: import("../..").Network;
9
+ activations: number[][];
10
+ flow: number;
11
+ };
12
+ export declare function layoutNetwork(item: NetworkItem, ctx: ItemContext): Shape[];
13
+ /** The cells a heatmap shows: given (optionally softmaxed by row) or sampled from its expression. */
14
+ export declare function heatmapCells(item: HeatmapItem, ctx: Pick<ItemContext, 'plane' | 'scope'>): {
15
+ cells: number[][];
16
+ box: [Vec2, Vec2];
17
+ };
18
+ export declare function layoutHeatmap(item: HeatmapItem, ctx: ItemContext): Shape[];
19
+ export declare function layoutContours(item: ContoursItem, ctx: ItemContext): Shape[];
20
+ /** The descent path so far: whole steps plus the fraction of the next. */
21
+ export declare function descentState(item: DescentItem, values: Values, scope: Record<string, number>): {
22
+ path: Vec2[];
23
+ here: Vec2;
24
+ step: number;
25
+ diverged: boolean;
26
+ };
27
+ export declare function layoutDescent(item: DescentItem, ctx: ItemContext): Shape[];
28
+ export declare function classifierState(item: ClassifierItem, values: Values): {
29
+ data: {
30
+ point: Vec2;
31
+ label: number;
32
+ }[];
33
+ model: LogisticModel;
34
+ epochs: number;
35
+ };
36
+ export declare function layoutClassifier(item: ClassifierItem, ctx: ItemContext): Shape[];
37
+ export declare function kmeansState(item: KMeansItem, values: Values): {
38
+ points: Vec2[];
39
+ history: Vec2[][];
40
+ centroids: Vec2[];
41
+ owners: number[];
42
+ iteration: number;
43
+ iterations: number;
44
+ };
45
+ export declare function layoutKMeans(item: KMeansItem, ctx: ItemContext): Shape[];
46
+ /** Derived numbers for the ML items, for TeX readouts. */
47
+ export declare function mlDerived(item: NetworkItem | DescentItem | ClassifierItem | KMeansItem, values: Values, scope: Record<string, number>): Record<string, number>;
@@ -23,6 +23,12 @@ export { ballPath, ballAt, binOf } from './prob/galton';
23
23
  export { bayesAreas, type BayesAreas } from './prob/bayes';
24
24
  export { searchEvents, treeLayout, adjacency, SEARCH_KINDS, type SearchKind, type SearchEvent, type GraphEdge } from './discrete/graph-search';
25
25
  export { parseSetExpression, inRegion, regionCells, setNames, type SetExpression } from './discrete/set-expression';
26
+ export { seededNetwork, forward, activate, ACTIVATIONS, type Network, type Activation } from './ml/network';
27
+ export { contourLines, sampleGrid } from './ml/contours';
28
+ export { descentPath, surface } from './ml/descent';
29
+ export { blobs, trainLogistic, predict, accuracy, logLoss, type LogisticModel } from './ml/classify';
30
+ export { kmeansHistory, assign, inertia } from './ml/kmeans';
31
+ export { colorAt, blendOver, COLORMAPS, type Colormap } from './ml/colormap';
26
32
  export { parseTex, TexError, TEX_COMMANDS, SYMBOLS, type TexNode, type TexClass } from './tex/tex-parser';
27
33
  export { layoutTex, type TexLayout, type TexPiece, type TexGlyph, type TexRule, type TexStroke, type TexLayoutOptions } from './tex/tex-layout';
28
34
  export { morphEquation, type MorphPiece, type PlacedLayout } from './tex/equation-morph';
@@ -37,11 +43,13 @@ export { displayListToSvg, displayListToSvgContent } from './render/display-list
37
43
  export { mathTarget, mathFigureProps, type MathCanvasTarget } from './targets/math-target';
38
44
  export { mathSteps, type MathSteps } from './steps/math-steps';
39
45
  export { mountMath, mountAllMath, type MountedMathFigure } from './embed/mount-math';
46
+ export { mathSurface, MATH_SURFACE, type MathSurface, type MathSurfaceBox, type MathSurfaceEdit } from './surface/math-surface';
40
47
  export { mathExplorable, type MathExplorable, type ExplorableOptions, type SliderControl, type DragHandle } from './embed/explorable';
41
48
  export { linearMapFigure, determinantFigure, eigenFigure, vectorSumFigure, spanFigure, MATRIX_TEX, type PresetOptions, } from './presets/linear-algebra';
42
49
  export { tangentFigure, secantFigure, riemannFigure, areaFigure, taylorFigure, limitFigure, type CalculusOptions } from './presets/calculus';
43
50
  export { normalFigure, binomialFigure, cltFigure, galtonFigure, monteCarloPiFigure, regressionFigure, bayesFigure, type ProbabilityOptions } from './presets/probability';
44
51
  export { graphSearchFigure, shortestPathFigure, recursionTreeFigure, vennFigure, clockFigure, SAMPLE_GRAPH, type DiscreteOptions } from './presets/discrete';
52
+ export { neuralNetworkFigure, gradientDescentFigure, attentionFigure, decisionBoundaryFigure, kmeansFigure, activationFigure, type MlOptions } from './presets/ml';
45
53
  import type { MathFigureSpec } from './figure/figure-spec';
46
54
  import { type MathProps } from './figure/layout-figure';
47
55
  /** A figure checked up front: returns it unchanged, or throws a message that says how to fix it. */
@@ -0,0 +1,30 @@
1
+ import type { Vec2 } from '../linear/vec2';
2
+ /** Points in clusters round `centres`, `count` per cluster, `spread` apart: [point, cluster] pairs. Seeded. */
3
+ export declare function blobs(centres: Vec2[], count: number, spread: number, seed: number | string): {
4
+ point: Vec2;
5
+ label: number;
6
+ }[];
7
+ export interface LogisticModel {
8
+ w: Vec2;
9
+ b: number;
10
+ }
11
+ /** P(class 1) for a point. */
12
+ export declare const predict: (model: LogisticModel, [x, y]: Vec2) => number;
13
+ /**
14
+ * Logistic regression trained by full-batch gradient descent from `start`
15
+ * (default zero weights): the model after each epoch, the start first.
16
+ */
17
+ export declare function trainLogistic(data: {
18
+ point: Vec2;
19
+ label: number;
20
+ }[], epochs: number, rate: number, start?: LogisticModel): LogisticModel[];
21
+ /** Share of points the model puts on the right side of 0.5. */
22
+ export declare function accuracy(model: LogisticModel, data: {
23
+ point: Vec2;
24
+ label: number;
25
+ }[]): number;
26
+ /** Mean cross-entropy loss. */
27
+ export declare function logLoss(model: LogisticModel, data: {
28
+ point: Vec2;
29
+ label: number;
30
+ }[]): number;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Colour scales for heatmaps, as plain functions of 0..1 (clamped):
3
+ * `viridis` (dark blue to yellow, readable in grey), `heat` (dark to orange
4
+ * to pale yellow), `diverging` (blue, white, red; for signed values).
5
+ */
6
+ export type Colormap = 'viridis' | 'heat' | 'diverging';
7
+ export declare const COLORMAPS: readonly Colormap[];
8
+ export declare function colorAt(map: Colormap, t: number): string;
9
+ /**
10
+ * `color` laid over `background` at `amount` (0..1), as one opaque colour.
11
+ * Neighbouring cells drawn this way can overlap without the darker seams
12
+ * that overlapping translucent fills leave.
13
+ */
14
+ export declare function blendOver(color: string, background: string, amount: number): string;
@@ -0,0 +1,15 @@
1
+ import type { Vec2 } from '../linear/vec2';
2
+ /**
3
+ * Level curves of a sampled function by marching squares: for each level,
4
+ * the line segments where the grid crosses it, joined into polylines.
5
+ * `values[j][i]` is f at x = x0 + i·dx, y = y0 + j·dy. Pure.
6
+ */
7
+ export declare function contourLines(values: number[][], x0: number, y0: number, dx: number, dy: number, level: number): Vec2[][];
8
+ /** f sampled on a grid over [x0, x1] × [y0, y1] with `n` + 1 points each way. */
9
+ export declare function sampleGrid(f: (x: number, y: number) => number, [x0, x1]: [number, number], [y0, y1]: [number, number], n: number): {
10
+ values: number[][];
11
+ x0: number;
12
+ y0: number;
13
+ dx: number;
14
+ dy: number;
15
+ };
@@ -0,0 +1,11 @@
1
+ import { type Scope } from '../expr/evaluate';
2
+ import type { Vec2 } from '../linear/vec2';
3
+ /**
4
+ * Gradient descent on f(x, y), with the gradient worked out symbolically:
5
+ * each step moves against the gradient by `rate`, plus `momentum` times the
6
+ * last step. Returns every point visited, the start first. Stops early if a
7
+ * step leaves the real numbers (a rate too large can diverge).
8
+ */
9
+ export declare function descentPath(expr: string, start: Vec2, rate: number, steps: number, momentum?: number, scope?: Scope): Vec2[];
10
+ /** A parsed f(x, y) to evaluate many times. */
11
+ export declare function surface(expr: string): (x: number, y: number, scope?: Scope) => number;
@@ -0,0 +1,11 @@
1
+ import type { Vec2 } from '../linear/vec2';
2
+ /** The centroid each point is nearest to (ties go to the lower index). */
3
+ export declare function assign(points: Vec2[], centroids: Vec2[]): number[];
4
+ /**
5
+ * Lloyd's algorithm from `start` (default the first `k` points), so it is
6
+ * deterministic: the centroids after each iteration, the start first,
7
+ * until they stop moving or `maxIterations` is reached.
8
+ */
9
+ export declare function kmeansHistory(points: Vec2[], k: number, maxIterations?: number, start?: Vec2[]): Vec2[][];
10
+ /** Sum of squared distances from each point to its centroid. */
11
+ export declare function inertia(points: Vec2[], centroids: Vec2[]): number;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A small fully connected network, for drawing: layer sizes, seeded weights
3
+ * and a forward pass. Pure: the same layers, seed and inputs always give the
4
+ * same weights and activations.
5
+ */
6
+ export type Activation = 'sigmoid' | 'tanh' | 'relu';
7
+ export declare const ACTIVATIONS: readonly Activation[];
8
+ export declare const activate: (kind: Activation, x: number) => number;
9
+ export interface Network {
10
+ layers: number[];
11
+ /** weights[l][j][i]: from node i of layer l to node j of layer l + 1 */
12
+ weights: number[][][];
13
+ /** biases[l][j]: of node j of layer l + 1 */
14
+ biases: number[][];
15
+ }
16
+ /** A network with weights drawn from a seed (normal, scaled by 1/√fan-in). */
17
+ export declare function seededNetwork(layers: number[], seed: number | string): Network;
18
+ /** Every layer's activations for `inputs` (layer 0 is the inputs themselves). */
19
+ export declare function forward(network: Network, inputs: number[], activation: Activation): number[][];
@@ -0,0 +1,50 @@
1
+ import type { MathFigureSpec, MathThemeName } from '../figure/figure-spec';
2
+ import type { Activation } from '../ml/network';
3
+ /**
4
+ * Ready-made AI/ML figures. Each returns a plain MathFigureSpec whose moving
5
+ * part is a number value:
6
+ *
7
+ * - neuralNetworkFigure: `flow` (how far activations have travelled) and inputs `in0`, `in1` …
8
+ * - gradientDescentFigure: `steps`, with `rate` and `momentum`
9
+ * - attentionFigure: no values; animate the heatmap's draw
10
+ * - decisionBoundaryFigure: `epochs`
11
+ * - kmeansFigure: `iteration`
12
+ * - activationFigure: no values
13
+ */
14
+ export interface MlOptions {
15
+ width?: number;
16
+ height?: number;
17
+ theme?: MathThemeName;
18
+ }
19
+ /** A small network; activations flow from the inputs to the outputs as `flow` goes 0 → layers − 1. */
20
+ export declare function neuralNetworkFigure(options?: MlOptions & {
21
+ layers?: number[];
22
+ activation?: Activation;
23
+ inputs?: number[];
24
+ seed?: string;
25
+ }): MathFigureSpec;
26
+ /** Gradient descent on a long, narrow bowl: a small rate crawls, a large one zigzags, momentum speeds it up. */
27
+ export declare function gradientDescentFigure(options?: MlOptions & {
28
+ expr?: string;
29
+ start?: [number, number];
30
+ rate?: number;
31
+ momentum?: number;
32
+ }): MathFigureSpec;
33
+ /** Attention weights between tokens: each row (a query) softmaxed over the columns (the keys). */
34
+ export declare function attentionFigure(options?: MlOptions & {
35
+ tokens?: string[];
36
+ scores?: number[][];
37
+ seed?: string;
38
+ }): MathFigureSpec;
39
+ /** Logistic regression finding the line between two clusters, epoch by epoch. */
40
+ export declare function decisionBoundaryFigure(options?: MlOptions & {
41
+ rate?: number;
42
+ spread?: number;
43
+ }): MathFigureSpec;
44
+ /** k-means finding clusters: points recolour as the centroids move. */
45
+ export declare function kmeansFigure(options?: MlOptions & {
46
+ centres?: [number, number][];
47
+ k?: number;
48
+ }): MathFigureSpec;
49
+ /** The usual activation functions side by side. */
50
+ export declare function activationFigure(options?: MlOptions): MathFigureSpec;
@@ -0,0 +1,69 @@
1
+ import type { EasingType, Track } from '../../engine/types';
2
+ import type { MathFigureSpec } from '../figure/figure-spec';
3
+ import { type MathCanvasTarget } from '../targets/math-target';
4
+ /**
5
+ * A maths figure as a surface figures act on, the way a code panel or a
6
+ * whiteboard is one: its places have names, so a beat can point at them as
7
+ * plain data, and its edits are recorded on the figure's own props.
8
+ *
9
+ * const fig = mathSurface(linearMapFigure(), { x: 40, y: 40 })
10
+ * surfaceScript('teacher', { fig }, [
11
+ * { do: 'point', target: { surface: 'fig', anchor: 'tip:basis.i' }, say: 'î lands here',
12
+ * then: { surface: 'fig', edit: 'set', anchor: 'value:M', value: [2, 1, 0, 1] } },
13
+ * ], { from: 640, ground: 400 })
14
+ *
15
+ * It has the shape of the characters module's Surface without importing it,
16
+ * so the maths module stays independent of characters. Parts of a figure do
17
+ * not come loose: `piece`, `follow`, `fling` and `move` say so.
18
+ */
19
+ export interface MathSurfaceBox {
20
+ x: number;
21
+ y: number;
22
+ left: number;
23
+ right: number;
24
+ top: number;
25
+ bottom: number;
26
+ width: number;
27
+ height: number;
28
+ }
29
+ export interface MathSurfaceEdit {
30
+ /** When, ms */
31
+ at: number;
32
+ duration?: number;
33
+ easing?: EasingType;
34
+ /** `set`: the new value (a number, [x, y] or [a, b, c, d]); `step`: the equation step */
35
+ value?: number | number[];
36
+ to?: number;
37
+ }
38
+ export interface MathSurface {
39
+ readonly kind: 'math';
40
+ readonly target: MathCanvasTarget;
41
+ readonly box: MathSurfaceBox;
42
+ readonly about: {
43
+ kind: string;
44
+ create: string;
45
+ anchors: Record<string, string>;
46
+ edits: Record<string, string>;
47
+ };
48
+ /** The box round a named place, scene px, as the figure is at `time` (default after every edit) */
49
+ anchor(name: string, time?: number): MathSurfaceBox;
50
+ /** Change the figure at a time (see `about.edits`) */
51
+ edit(name: string, anchor: string | string[], options: MathSurfaceEdit): MathSurface;
52
+ piece(anchor: string): never;
53
+ follow(): never;
54
+ fling(): never;
55
+ move(): never;
56
+ /** Figures standing on a maths figure are not carried: their tracks come back as they are */
57
+ ride(tracks: Track[], target: string, options: {
58
+ ground: number;
59
+ every?: number;
60
+ }): Track[];
61
+ /** The recorded edits as tracks on `target` (the figure's key in the scene) */
62
+ tracks(target: string): Track[];
63
+ }
64
+ export declare const MATH_SURFACE: MathSurface['about'];
65
+ /** A maths figure placed at `x`, `y` (its top-left corner, scene px) as a surface. */
66
+ export declare function mathSurface(figure: MathFigureSpec, place?: {
67
+ x?: number;
68
+ y?: number;
69
+ }): MathSurface;