@tinyvolt/pie 0.9.0 → 0.10.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.
- package/README.md +18 -1
- package/dist/components/SplitPane.d.ts +21 -0
- package/dist/components/SplitPane.jsx +113 -0
- package/dist/components/icons.d.ts +12 -0
- package/dist/components/icons.jsx +45 -0
- package/dist/lib/autodiff/index.d.ts +28 -0
- package/dist/lib/autodiff/index.js +39 -0
- package/dist/lib/customModules.d.ts +13 -0
- package/dist/lib/customModules.js +17 -0
- package/dist/lib/markdown/compile.d.ts +27 -0
- package/dist/lib/markdown/compile.js +26 -0
- package/dist/lib/markdown/components/CanvasPage.d.ts +9 -0
- package/dist/lib/markdown/components/CanvasPage.jsx +16 -0
- package/dist/lib/markdown/components/MarkdownBody.d.ts +11 -0
- package/dist/lib/markdown/components/MarkdownBody.jsx +37 -0
- package/dist/lib/markdown/components/PiePage.d.ts +14 -0
- package/dist/lib/markdown/components/PiePage.jsx +41 -0
- package/dist/lib/markdown/components/PythonEditor.d.ts +10 -0
- package/dist/lib/markdown/components/PythonEditor.jsx +209 -0
- package/dist/lib/markdown/features/build.d.ts +60 -0
- package/dist/lib/markdown/features/build.js +36 -0
- package/dist/lib/markdown/features/glossary/View.d.ts +9 -0
- package/dist/lib/markdown/features/glossary/View.jsx +62 -0
- package/dist/lib/markdown/features/glossary/build.d.ts +6 -0
- package/dist/lib/markdown/features/glossary/build.js +81 -0
- package/dist/lib/markdown/features/sidebar/View.d.ts +11 -0
- package/dist/lib/markdown/features/sidebar/View.jsx +45 -0
- package/dist/lib/markdown/features/sidebar/build.d.ts +3 -0
- package/dist/lib/markdown/features/sidebar/build.js +7 -0
- package/dist/lib/markdown/features/tags/build.d.ts +7 -0
- package/dist/lib/markdown/features/tags/build.js +22 -0
- package/dist/lib/markdown/features/tags/url.d.ts +6 -0
- package/dist/lib/markdown/features/tags/url.js +10 -0
- package/dist/lib/markdown/features/toc/build.d.ts +7 -0
- package/dist/lib/markdown/features/toc/build.js +62 -0
- package/dist/lib/markdown/features/views.d.ts +4 -0
- package/dist/lib/markdown/features/views.jsx +11 -0
- package/dist/lib/markdown/frontmatter.d.ts +44 -0
- package/dist/lib/markdown/frontmatter.js +109 -0
- package/dist/lib/markdown/render.d.ts +6 -0
- package/dist/lib/markdown/render.js +95 -0
- package/dist/lib/nodes/animation.d.ts +14 -0
- package/dist/lib/nodes/animation.js +34 -0
- package/dist/lib/nodes/components/CenteredGrid.d.ts +20 -0
- package/dist/lib/nodes/components/CenteredGrid.jsx +44 -0
- package/dist/lib/nodes/components/NodeCanvas.d.ts +7 -0
- package/dist/lib/nodes/components/NodeCanvas.jsx +50 -0
- package/dist/lib/nodes/execute.d.ts +27 -0
- package/dist/lib/nodes/execute.js +159 -0
- package/dist/lib/nodes/functions/Node2NodeFunc.d.ts +70 -0
- package/dist/lib/nodes/functions/Node2NodeFunc.js +223 -0
- package/dist/lib/nodes/functions/array.d.ts +12 -0
- package/dist/lib/nodes/functions/array.js +31 -0
- package/dist/lib/nodes/functions/autodiff.d.ts +12 -0
- package/dist/lib/nodes/functions/autodiff.js +60 -0
- package/dist/lib/nodes/functions/basic.d.ts +111 -0
- package/dist/lib/nodes/functions/basic.js +275 -0
- package/dist/lib/nodes/functions/registry.d.ts +9 -0
- package/dist/lib/nodes/functions/registry.js +45 -0
- package/dist/lib/nodes/functions/sideEffects.d.ts +78 -0
- package/dist/lib/nodes/functions/sideEffects.js +201 -0
- package/dist/lib/nodes/hooks/useCanvasGestures.d.ts +9 -0
- package/dist/lib/nodes/hooks/useCanvasGestures.js +120 -0
- package/dist/lib/nodes/hooks/useCanvasResize.d.ts +2 -0
- package/dist/lib/nodes/hooks/useCanvasResize.js +33 -0
- package/dist/lib/nodes/jax.d.ts +46 -0
- package/dist/lib/nodes/jax.js +120 -0
- package/dist/lib/nodes/render/renderLogic.d.ts +13 -0
- package/dist/lib/nodes/render/renderLogic.jsx +234 -0
- package/dist/lib/nodes/state/NameGenerator.d.ts +10 -0
- package/dist/lib/nodes/state/NameGenerator.js +29 -0
- package/dist/lib/nodes/state/Node.d.ts +134 -0
- package/dist/lib/nodes/state/Node.js +57 -0
- package/dist/lib/nodes/state/NodeStore.d.ts +49 -0
- package/dist/lib/nodes/state/NodeStore.js +138 -0
- package/dist/lib/nodes/tensors/broadcast.d.ts +18 -0
- package/dist/lib/nodes/tensors/broadcast.js +92 -0
- package/dist/lib/nodes/tensors/tensor.d.ts +13 -0
- package/dist/lib/nodes/tensors/tensor.js +34 -0
- package/dist/lib/python/lift.d.ts +51 -0
- package/dist/lib/python/lift.js +155 -0
- package/dist/lib/python/py/pie.py +303 -0
- package/dist/lib/python/py/pie_mpl.py +15 -0
- package/dist/lib/python/py/show_figures.py +5 -0
- package/dist/lib/python/runner.d.ts +36 -0
- package/dist/lib/python/runner.js +221 -0
- package/dist/lib/python/worker.d.ts +1 -0
- package/dist/lib/python/worker.js +111 -0
- package/dist/lib/ui/UiLayer.d.ts +2 -0
- package/dist/lib/ui/UiLayer.jsx +15 -0
- package/dist/lib/ui/UiView.d.ts +23 -0
- package/dist/lib/ui/UiView.jsx +56 -0
- package/dist/lib/ui/components/checkboxes.d.ts +10 -0
- package/dist/lib/ui/components/checkboxes.jsx +30 -0
- package/dist/lib/ui/components/latex.d.ts +8 -0
- package/dist/lib/ui/components/latex.jsx +41 -0
- package/dist/lib/ui/components/radio.d.ts +6 -0
- package/dist/lib/ui/components/radio.jsx +19 -0
- package/dist/lib/ui/components/slider.d.ts +8 -0
- package/dist/lib/ui/components/slider.jsx +7 -0
- package/dist/lib/ui/components/textbox.d.ts +5 -0
- package/dist/lib/ui/components/textbox.jsx +21 -0
- package/dist/lib/ui/dragUi.d.ts +10 -0
- package/dist/lib/ui/dragUi.js +129 -0
- package/dist/lib/ui/nodeHandle.d.ts +15 -0
- package/dist/lib/ui/nodeHandle.js +37 -0
- package/dist/lib/ui/registry.d.ts +10 -0
- package/dist/lib/ui/registry.js +42 -0
- package/dist/runtime.css +696 -0
- package/dist/runtime.d.ts +9 -0
- package/dist/runtime.jsx +6 -0
- package/init/index.js +2 -2
- package/init/site-agents.md +2 -1
- package/package.json +15 -6
- package/runtime-agents.md +146 -0
- package/src/app.css +7 -665
- package/src/lib/customModules.ts +30 -0
- package/src/lib/markdown/compile.ts +49 -0
- package/src/lib/markdown/components/PiePage.tsx +48 -0
- package/src/lib/markdown/features/build.ts +15 -6
- package/src/lib/markdown/features/sidebar/View.tsx +4 -2
- package/src/lib/markdown/features/tags/build.ts +6 -3
- package/src/lib/markdown/pages.ts +1 -9
- package/src/lib/markdown/vitePlugin.ts +4 -8
- package/src/lib/nodes/functions/registry.ts +30 -21
- package/src/lib/nodes/functions/sideEffects.ts +14 -8
- package/src/lib/nodes/functions/vitePlugin.ts +8 -10
- package/src/lib/nodes/state/Node.ts +27 -19
- package/src/lib/siteModules.ts +13 -0
- package/src/lib/ui/dragUi.ts +4 -2
- package/src/lib/ui/registry.ts +35 -14
- package/src/page.css +664 -0
- package/src/routes/[...slug].tsx +1 -0
- package/src/runtime.css +29 -0
- package/src/runtime.tsx +15 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const DUMMY = { id: '', type: 'Dummy' };
|
|
2
|
+
/** Whether an input of type `type` is looped over: an array going to a parameter that doesn't take whole arrays. */
|
|
3
|
+
export function isBroadcast(type, param) {
|
|
4
|
+
const types = Array.isArray(param.type) ? param.type : [param.type];
|
|
5
|
+
return type === 'Array' && !types.includes('Array');
|
|
6
|
+
}
|
|
7
|
+
const formatShape = (shape) => `(${shape.join(', ')}${shape.length === 1 ? ',' : ''})`;
|
|
8
|
+
/** numpy broadcasting: shapes are lined up from the right, and each dimension must match or be 1. */
|
|
9
|
+
export function broadcastShapes(shapes) {
|
|
10
|
+
const ndim = Math.max(...shapes.map(shape => shape.length));
|
|
11
|
+
const result = [];
|
|
12
|
+
for (let d = 0; d < ndim; d++) {
|
|
13
|
+
let size = 1;
|
|
14
|
+
for (const shape of shapes) {
|
|
15
|
+
const dim = shape[d - ndim + shape.length] ?? 1;
|
|
16
|
+
if (dim === 1)
|
|
17
|
+
continue;
|
|
18
|
+
if (size !== 1 && size !== dim) {
|
|
19
|
+
throw new Error(`shapes ${shapes.map(formatShape).join(' and ')} can't be broadcast together`);
|
|
20
|
+
}
|
|
21
|
+
size = dim;
|
|
22
|
+
}
|
|
23
|
+
result.push(size);
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
/** Row-major position `flat` as one index per dimension of `shape`. */
|
|
28
|
+
function unravel(flat, shape) {
|
|
29
|
+
const index = [];
|
|
30
|
+
for (let d = shape.length - 1; d >= 0; d--) {
|
|
31
|
+
index[d] = flat % shape[d];
|
|
32
|
+
flat = Math.floor(flat / shape[d]);
|
|
33
|
+
}
|
|
34
|
+
return index;
|
|
35
|
+
}
|
|
36
|
+
/** The row-major position in an array of `shape` that broadcast output index `index` reads. */
|
|
37
|
+
function sourceIndex(shape, index) {
|
|
38
|
+
const offset = index.length - shape.length;
|
|
39
|
+
return shape.reduce((flat, dim, d) => flat * dim + (dim === 1 ? 0 : index[d + offset]), 0);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The inputs of each item when an input is broadcast (see `isBroadcast`), or just `inputs`
|
|
43
|
+
* when none is. Like `computeBlueprint`, an item with a Dummy input is skipped.
|
|
44
|
+
*/
|
|
45
|
+
export function broadcastItems(parameters, inputs) {
|
|
46
|
+
// An input is undefined for a left-out optional parameter.
|
|
47
|
+
const broadcasts = inputs.map((node, i) => node !== undefined && isBroadcast(node.type, parameters[i]));
|
|
48
|
+
if (!broadcasts.includes(true))
|
|
49
|
+
return [inputs];
|
|
50
|
+
const shapes = inputs.map((node, i) => broadcasts[i] ? node.shape : []);
|
|
51
|
+
const shape = broadcastShapes(shapes);
|
|
52
|
+
const size = shape.reduce((a, b) => a * b, 1);
|
|
53
|
+
const items = [];
|
|
54
|
+
for (let k = 0; k < size; k++) {
|
|
55
|
+
const index = unravel(k, shape);
|
|
56
|
+
const itemInputs = inputs.map((node, i) => broadcasts[i] ? node.items[sourceIndex(shapes[i], index)] : node);
|
|
57
|
+
if (!itemInputs.some(node => node?.type === 'Dummy'))
|
|
58
|
+
items.push(itemInputs);
|
|
59
|
+
}
|
|
60
|
+
return items;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* `func.compute`, run once per item when an input is broadcast (see `isBroadcast`).
|
|
64
|
+
* Item k's nodes are saved under keys `k.main`, `k.l_0`, ..., and `main` is the array of
|
|
65
|
+
* every item's main node. An item is Dummy, and not saved, when one of its inputs is
|
|
66
|
+
* Dummy or its own main node is.
|
|
67
|
+
*/
|
|
68
|
+
export function computeBlueprint(func, inputs) {
|
|
69
|
+
// An input is undefined for a left-out optional parameter.
|
|
70
|
+
const broadcasts = inputs.map((node, i) => node !== undefined && isBroadcast(node.type, func.parameters[i]));
|
|
71
|
+
if (!broadcasts.includes(true))
|
|
72
|
+
return func.compute(inputs);
|
|
73
|
+
const shapes = inputs.map((node, i) => broadcasts[i] ? node.shape : []);
|
|
74
|
+
const shape = broadcastShapes(shapes);
|
|
75
|
+
const size = shape.reduce((a, b) => a * b, 1);
|
|
76
|
+
const blueprint = {};
|
|
77
|
+
const items = [];
|
|
78
|
+
for (let k = 0; k < size; k++) {
|
|
79
|
+
const index = unravel(k, shape);
|
|
80
|
+
const itemInputs = inputs.map((node, i) => broadcasts[i] ? node.items[sourceIndex(shapes[i], index)] : node);
|
|
81
|
+
const item = itemInputs.some(node => node?.type === 'Dummy') ? { main: DUMMY } : func.compute(itemInputs);
|
|
82
|
+
if (item.main.type === 'Dummy') {
|
|
83
|
+
items.push(DUMMY);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
for (const key in item)
|
|
87
|
+
blueprint[`${k}.${key}`] = item[key];
|
|
88
|
+
items.push(item.main);
|
|
89
|
+
}
|
|
90
|
+
blueprint.main = { type: 'Array', itemType: func.outputType, shape, items };
|
|
91
|
+
return blueprint;
|
|
92
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Arg, ExecuteResult } from '../execute';
|
|
2
|
+
import type { NodeStore } from '../state/NodeStore';
|
|
3
|
+
import { NodeType } from '../state/Node';
|
|
4
|
+
export type LeafArg = Exclude<Arg, Arg[]>;
|
|
5
|
+
/** The items of a nested list, in row-major order. */
|
|
6
|
+
export declare const leaves: (list: Arg[]) => LeafArg[];
|
|
7
|
+
/** A nested list's shape: [[a, b], [c, d]] has shape [2, 2]. */
|
|
8
|
+
export declare function listShape(list: Arg[]): number[];
|
|
9
|
+
export declare function sha256(text: string): Promise<string>;
|
|
10
|
+
/** The node at `position` of array `arrayId`'s items. Creates nothing. */
|
|
11
|
+
export declare function getItem(store: NodeStore, arrayId: string, position: number): ExecuteResult;
|
|
12
|
+
/** The one type all items of a nested list share, or 'Mixed' when they differ. `typeOf` gives an item's type. */
|
|
13
|
+
export declare function listItemType(list: Arg[], typeOf: (item: LeafArg) => string): NodeType | 'Mixed';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The items of a nested list, in row-major order. */
|
|
2
|
+
export const leaves = (list) => list.flatMap(item => Array.isArray(item) ? leaves(item) : [item]);
|
|
3
|
+
/** A nested list's shape: [[a, b], [c, d]] has shape [2, 2]. */
|
|
4
|
+
export function listShape(list) {
|
|
5
|
+
if (list.length === 0)
|
|
6
|
+
throw new Error('a list must not be empty');
|
|
7
|
+
const shapes = list.map(item => Array.isArray(item) ? listShape(item) : []);
|
|
8
|
+
if (shapes.some(shape => shape.join() !== shapes[0].join())) {
|
|
9
|
+
throw new Error('nested lists must all have the same length');
|
|
10
|
+
}
|
|
11
|
+
return [list.length, ...shapes[0]];
|
|
12
|
+
}
|
|
13
|
+
export async function sha256(text) {
|
|
14
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
15
|
+
return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
|
|
16
|
+
}
|
|
17
|
+
/** The node at `position` of array `arrayId`'s items. Creates nothing. */
|
|
18
|
+
export function getItem(store, arrayId, position) {
|
|
19
|
+
const array = store.getNodeValue(arrayId);
|
|
20
|
+
if (array?.type !== 'Array')
|
|
21
|
+
throw new Error(`'${arrayId}' is not an array`);
|
|
22
|
+
const item = array.items[position];
|
|
23
|
+
if (item.type === 'Dummy')
|
|
24
|
+
throw new Error(`item ${position} of '${arrayId}' is Dummy`);
|
|
25
|
+
return { id: item.id, type: item.type };
|
|
26
|
+
}
|
|
27
|
+
/** The one type all items of a nested list share, or 'Mixed' when they differ. `typeOf` gives an item's type. */
|
|
28
|
+
export function listItemType(list, typeOf) {
|
|
29
|
+
listShape(list);
|
|
30
|
+
const types = new Set(leaves(list).map(typeOf));
|
|
31
|
+
if (types.size > 1)
|
|
32
|
+
return 'Mixed';
|
|
33
|
+
return [...types][0];
|
|
34
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { NodeStore } from '../nodes/state/NodeStore';
|
|
2
|
+
/** The type passed to `pie.lift`: `pie.Scalar`, `pie.Point`, `pie.Text`, or `pie.Array[...]` of `itemType`. */
|
|
3
|
+
type Kind = 'Scalar' | 'Point' | 'Text' | 'Array';
|
|
4
|
+
type ItemType = 'Scalar' | 'Point';
|
|
5
|
+
/** An input node's value as Python gets it: a Scalar's number, a Point's [x, y], a Text's string, or an Array's values in row-major order. */
|
|
6
|
+
export type InputValue = number | [number, number] | string | PyResult;
|
|
7
|
+
/** A result from Python. `values`: every number in row-major order, a Point as x, y; or a Text's string. A Scalar, Point or Text has shape []. */
|
|
8
|
+
export interface PyResult {
|
|
9
|
+
shape: number[];
|
|
10
|
+
values: number[] | [string];
|
|
11
|
+
}
|
|
12
|
+
/** Sent by Python once `g(a)`, for `g = pie.lift(f, ...)`, has its first result. */
|
|
13
|
+
export interface LiftSave extends PyResult {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
inputIds: string[];
|
|
17
|
+
kind: Kind;
|
|
18
|
+
itemType?: ItemType;
|
|
19
|
+
hidden: boolean;
|
|
20
|
+
fill?: string;
|
|
21
|
+
stroke?: string;
|
|
22
|
+
}
|
|
23
|
+
export type Rerun = (nodeId: string, values: InputValue[], done: (result?: PyResult, error?: string) => void) => void;
|
|
24
|
+
/** Before an animation: run node `nodeId`'s lifted function once per entry of `inputs`, one per step. */
|
|
25
|
+
export interface BatchJob {
|
|
26
|
+
nodeId: string;
|
|
27
|
+
inputs: InputValue[][];
|
|
28
|
+
}
|
|
29
|
+
/** The function's result for one entry of a job's `inputs`, or the error it raised. */
|
|
30
|
+
export type BatchResult = PyResult | {
|
|
31
|
+
error: string;
|
|
32
|
+
};
|
|
33
|
+
/** First half of `g(a)`: checks the inputs, `out`, `fill` and `stroke`, and reserves the output id. Python then calls `f` with `values`. */
|
|
34
|
+
export declare function startLift(store: NodeStore, name: string, inputIds: string[], kind: Kind, out?: string, fill?: string, stroke?: string): {
|
|
35
|
+
id: string;
|
|
36
|
+
values: InputValue[];
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Before an animation: gets every lifted result its steps need from `runBatch`, one trip for all of them.
|
|
40
|
+
* `visitSteps` shows each step, and the lifted nodes note the inputs they have no result for. A result
|
|
41
|
+
* can change the inputs of a lifted node that depends on it, so this repeats until nothing is missing.
|
|
42
|
+
* Returns the function that ends the animation for these nodes. Errors go to the console.
|
|
43
|
+
*/
|
|
44
|
+
export declare function prepareLifts(visitSteps: () => void, runBatch: (jobs: BatchJob[]) => Promise<BatchResult[][]>): Promise<() => void>;
|
|
45
|
+
/**
|
|
46
|
+
* Second half of `g(a)`: saves the node with Python's first result. When an input's value changes,
|
|
47
|
+
* the node keeps its value and asks `rerun` for a new one. Rerun errors go to the console.
|
|
48
|
+
* During an animation it shows the results `prepareLifts` got for the steps instead.
|
|
49
|
+
*/
|
|
50
|
+
export declare function saveLift(store: NodeStore, save: LiftSave, rerun: Rerun): void;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createSignal } from 'solid-js';
|
|
2
|
+
import { NodeReconciler, PYTHON_KEYWORD_PREFIX } from '../nodes/functions/Node2NodeFunc';
|
|
3
|
+
import { checkOut } from '../nodes/execute';
|
|
4
|
+
import { checkColor } from '../nodes/state/Node';
|
|
5
|
+
import { num, scalar } from '../nodes/jax';
|
|
6
|
+
// Set while an animation's steps are visited: the inputs each lifted node has no result for, by input values.
|
|
7
|
+
let missing;
|
|
8
|
+
function inputValue(node, id) {
|
|
9
|
+
if (!node)
|
|
10
|
+
throw new Error(`Unknown node '${id}'`);
|
|
11
|
+
if (node.type === 'Scalar')
|
|
12
|
+
return num(node.value);
|
|
13
|
+
if (node.type === 'Point')
|
|
14
|
+
return [num(node.x), num(node.y)];
|
|
15
|
+
if (node.type === 'Text')
|
|
16
|
+
return node.value;
|
|
17
|
+
if (node.type === 'Array') {
|
|
18
|
+
if (node.itemType === 'Mixed')
|
|
19
|
+
throw new Error(`'${id}' is an Array of mixed types; an Array input must hold one type`);
|
|
20
|
+
const values = node.items.flatMap(item => inputValue(item, item.id));
|
|
21
|
+
return { shape: node.itemType === 'Point' ? [...node.shape, 2] : node.shape, values };
|
|
22
|
+
}
|
|
23
|
+
throw new Error(`'${id}' is a ${node.type}; only Scalar, Point and Text nodes and Arrays of them can be inputs`);
|
|
24
|
+
}
|
|
25
|
+
/** First half of `g(a)`: checks the inputs, `out`, `fill` and `stroke`, and reserves the output id. Python then calls `f` with `values`. */
|
|
26
|
+
export function startLift(store, name, inputIds, kind, out, fill, stroke) {
|
|
27
|
+
const values = inputIds.map(id => inputValue(store.getNodeValue(id), id));
|
|
28
|
+
checkOut(name, out, inputIds.map(id => ({ id })));
|
|
29
|
+
checkColor(name, 'fill', fill);
|
|
30
|
+
checkColor(name, 'stroke', stroke);
|
|
31
|
+
const id = out ?? store.nameGenerator.generateAutoName(store.nameGenerator.getPrefixForType(kind));
|
|
32
|
+
return { id, values };
|
|
33
|
+
}
|
|
34
|
+
/** Item k of an Array is saved under key `k`, so a rerun with a new shape keeps, adds or removes items by position. */
|
|
35
|
+
function toBlueprint(kind, itemType, result) {
|
|
36
|
+
if (kind === 'Text')
|
|
37
|
+
return { main: { type: 'Text', value: result.values[0] } };
|
|
38
|
+
const { shape } = result;
|
|
39
|
+
const values = result.values;
|
|
40
|
+
const item = (type, k) => type === 'Point'
|
|
41
|
+
? { type: 'Point', x: scalar(values[2 * k]), y: scalar(values[2 * k + 1]) }
|
|
42
|
+
: { type: 'Scalar', value: scalar(values[k]) };
|
|
43
|
+
if (kind !== 'Array')
|
|
44
|
+
return { main: item(kind, 0) };
|
|
45
|
+
const blueprint = {};
|
|
46
|
+
const items = [];
|
|
47
|
+
const size = shape.reduce((a, b) => a * b, 1);
|
|
48
|
+
for (let k = 0; k < size; k++)
|
|
49
|
+
items.push(blueprint[k] = item(itemType, k));
|
|
50
|
+
blueprint.main = { type: 'Array', itemType, shape, items };
|
|
51
|
+
return blueprint;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Before an animation: gets every lifted result its steps need from `runBatch`, one trip for all of them.
|
|
55
|
+
* `visitSteps` shows each step, and the lifted nodes note the inputs they have no result for. A result
|
|
56
|
+
* can change the inputs of a lifted node that depends on it, so this repeats until nothing is missing.
|
|
57
|
+
* Returns the function that ends the animation for these nodes. Errors go to the console.
|
|
58
|
+
*/
|
|
59
|
+
export async function prepareLifts(visitSteps, runBatch) {
|
|
60
|
+
const animated = new Set();
|
|
61
|
+
for (;;) {
|
|
62
|
+
const found = new Map();
|
|
63
|
+
missing = found;
|
|
64
|
+
try {
|
|
65
|
+
visitSteps();
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
missing = undefined;
|
|
69
|
+
}
|
|
70
|
+
if (found.size === 0)
|
|
71
|
+
return () => animated.forEach(node => node.end());
|
|
72
|
+
const nodes = [...found.keys()];
|
|
73
|
+
const results = await runBatch(nodes.map(node => ({ nodeId: node.nodeId, inputs: [...found.get(node).values()] })));
|
|
74
|
+
nodes.forEach((node, i) => {
|
|
75
|
+
const keys = [...found.get(node).keys()];
|
|
76
|
+
node.save(new Map(keys.map((key, j) => [key, results[i][j]])));
|
|
77
|
+
animated.add(node);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Second half of `g(a)`: saves the node with Python's first result. When an input's value changes,
|
|
83
|
+
* the node keeps its value and asks `rerun` for a new one. Rerun errors go to the console.
|
|
84
|
+
* During an animation it shows the results `prepareLifts` got for the steps instead.
|
|
85
|
+
*/
|
|
86
|
+
export function saveLift(store, save, rerun) {
|
|
87
|
+
const { id, name, inputIds, kind, itemType, hidden, fill, stroke } = save;
|
|
88
|
+
const [blueprint, setBlueprint] = createSignal(toBlueprint(kind, itemType, save));
|
|
89
|
+
// The input values of the latest result or rerun request. Unset until the first compute, which uses the first result.
|
|
90
|
+
let requested;
|
|
91
|
+
// During an animation: the results for its steps, by input values. `null`: the function failed for them.
|
|
92
|
+
const steps = new Map();
|
|
93
|
+
// The input values of the step shown last.
|
|
94
|
+
let shownStep;
|
|
95
|
+
const animated = {
|
|
96
|
+
nodeId: id,
|
|
97
|
+
save(results) {
|
|
98
|
+
let error;
|
|
99
|
+
for (const [key, result] of results) {
|
|
100
|
+
if ('error' in result)
|
|
101
|
+
error ??= result.error;
|
|
102
|
+
steps.set(key, 'error' in result ? null : toBlueprint(kind, itemType, result));
|
|
103
|
+
}
|
|
104
|
+
if (error !== undefined)
|
|
105
|
+
console.error(`${name}: ${error}`);
|
|
106
|
+
},
|
|
107
|
+
end() {
|
|
108
|
+
if (shownStep === undefined)
|
|
109
|
+
return;
|
|
110
|
+
const shown = steps.get(shownStep);
|
|
111
|
+
requested = shownStep;
|
|
112
|
+
shownStep = undefined;
|
|
113
|
+
steps.clear();
|
|
114
|
+
if (shown)
|
|
115
|
+
setBlueprint(shown);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
const func = {
|
|
119
|
+
keyword: `${PYTHON_KEYWORD_PREFIX}${name}`,
|
|
120
|
+
outputType: kind,
|
|
121
|
+
// 'Array' too, so `computeBlueprint` passes an Array input whole instead of looping over it.
|
|
122
|
+
parameters: inputIds.map((_, i) => ({ name: `input${i}`, type: ['Scalar', 'Point', 'Text', 'Array'] })),
|
|
123
|
+
broadcastable: false,
|
|
124
|
+
compute(inputs) {
|
|
125
|
+
const values = inputs.map((node, i) => inputValue(node, inputIds[i]));
|
|
126
|
+
const key = JSON.stringify(values);
|
|
127
|
+
if (missing || steps.has(key)) {
|
|
128
|
+
const step = steps.get(key);
|
|
129
|
+
if (step === undefined)
|
|
130
|
+
noteMissing(animated, key, values);
|
|
131
|
+
else
|
|
132
|
+
shownStep = key;
|
|
133
|
+
return step ?? blueprint();
|
|
134
|
+
}
|
|
135
|
+
if (requested !== undefined && key !== requested) {
|
|
136
|
+
rerun(id, values, (result, error) => {
|
|
137
|
+
if (error !== undefined)
|
|
138
|
+
console.error(`${name}: ${error}`);
|
|
139
|
+
// A reply for an older request is dropped.
|
|
140
|
+
else if (key === requested)
|
|
141
|
+
setBlueprint(toBlueprint(kind, itemType, result));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
requested = key;
|
|
145
|
+
return blueprint();
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
new NodeReconciler().evaluate(func, inputIds, store, id, hidden, fill, stroke);
|
|
149
|
+
}
|
|
150
|
+
function noteMissing(node, key, values) {
|
|
151
|
+
let inputs = missing.get(node);
|
|
152
|
+
if (!inputs)
|
|
153
|
+
missing.set(node, inputs = new Map());
|
|
154
|
+
inputs.set(key, values);
|
|
155
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import json, numbers, sys, types
|
|
2
|
+
from pyodide.ffi import run_sync, to_js
|
|
3
|
+
from js import Object
|
|
4
|
+
import bridge
|
|
5
|
+
|
|
6
|
+
class Node:
|
|
7
|
+
def __init__(self, id, type):
|
|
8
|
+
self.id = id
|
|
9
|
+
self.type = type
|
|
10
|
+
|
|
11
|
+
def __repr__(self):
|
|
12
|
+
return f"{self.type}({self.id})"
|
|
13
|
+
|
|
14
|
+
class Scalar(Node):
|
|
15
|
+
def __init__(self, id):
|
|
16
|
+
super().__init__(id, "Scalar")
|
|
17
|
+
|
|
18
|
+
class Point(Node):
|
|
19
|
+
def __init__(self, id):
|
|
20
|
+
super().__init__(id, "Point")
|
|
21
|
+
|
|
22
|
+
class Text(Node):
|
|
23
|
+
def __init__(self, id):
|
|
24
|
+
super().__init__(id, "Text")
|
|
25
|
+
|
|
26
|
+
class Array(Node):
|
|
27
|
+
# `pie.Array[pie.Point]`, a type for `pie.lift`.
|
|
28
|
+
def __class_getitem__(cls, item):
|
|
29
|
+
return types.GenericAlias(cls, item)
|
|
30
|
+
|
|
31
|
+
def __init__(self, id, shape, item_type):
|
|
32
|
+
super().__init__(id, "Array")
|
|
33
|
+
self.shape = shape
|
|
34
|
+
self.item_type = item_type
|
|
35
|
+
|
|
36
|
+
def __len__(self):
|
|
37
|
+
return self.shape[0]
|
|
38
|
+
|
|
39
|
+
def __repr__(self):
|
|
40
|
+
return f"Array[{self.item_type}]({self.id}, shape={self.shape})"
|
|
41
|
+
|
|
42
|
+
def __getitem__(self, key):
|
|
43
|
+
key = key if isinstance(key, tuple) else (key,)
|
|
44
|
+
if len(key) > len(self.shape):
|
|
45
|
+
raise IndexError(f"too many indices: the array has {len(self.shape)} dimensions, got {len(key)}")
|
|
46
|
+
entries = [_index_entry(k, n) for k, n in zip(key, self.shape)]
|
|
47
|
+
# One int per dimension picks an existing item: no new node.
|
|
48
|
+
if len(entries) == len(self.shape) and all(isinstance(e, int) for e in entries):
|
|
49
|
+
position = 0
|
|
50
|
+
for e, n in zip(entries, self.shape):
|
|
51
|
+
position = position * n + e
|
|
52
|
+
_check_bridge()
|
|
53
|
+
return _node(run_sync(bridge.item(self.id, position)))
|
|
54
|
+
return _call("_index", [self, json.dumps(entries)])
|
|
55
|
+
|
|
56
|
+
def _index_entry(k, n):
|
|
57
|
+
"""One dimension of a key, for a dimension of size `n`: an int, or the list of ints a slice picks."""
|
|
58
|
+
if isinstance(k, slice):
|
|
59
|
+
return list(range(*k.indices(n)))
|
|
60
|
+
if isinstance(k, int):
|
|
61
|
+
if not -n <= k < n:
|
|
62
|
+
raise IndexError(f"index {k} is out of range for size {n}")
|
|
63
|
+
return k % n
|
|
64
|
+
raise TypeError(f"array indices must be ints or slices, got {type(k).__name__}")
|
|
65
|
+
|
|
66
|
+
def _node(result):
|
|
67
|
+
if result.type == "Array":
|
|
68
|
+
return Array(result.id, tuple(result.shape), result.itemType)
|
|
69
|
+
if result.type == "Scalar":
|
|
70
|
+
return Scalar(result.id)
|
|
71
|
+
if result.type == "Point":
|
|
72
|
+
return Point(result.id)
|
|
73
|
+
if result.type == "Text":
|
|
74
|
+
return Text(result.id)
|
|
75
|
+
return Node(result.id, result.type)
|
|
76
|
+
|
|
77
|
+
def get_node(id):
|
|
78
|
+
"""The existing node with id `id`, e.g. `a = pie.get_node("A")`. Creates nothing."""
|
|
79
|
+
if not isinstance(id, str):
|
|
80
|
+
raise TypeError(f"pie.get_node: id must be a str, got {type(id).__name__}")
|
|
81
|
+
_check_bridge()
|
|
82
|
+
return _node(run_sync(bridge.get_node(id)))
|
|
83
|
+
|
|
84
|
+
def _arg(a):
|
|
85
|
+
if isinstance(a, Node):
|
|
86
|
+
return {"id": a.id}
|
|
87
|
+
if isinstance(a, (list, tuple)):
|
|
88
|
+
return [_arg(x) for x in a]
|
|
89
|
+
return a
|
|
90
|
+
|
|
91
|
+
def _call(name, args, **options):
|
|
92
|
+
"""`options`: keyword arguments like `out` and `fill`. Ones that are None are left out."""
|
|
93
|
+
_check_bridge()
|
|
94
|
+
js_args = to_js([_arg(a) for a in args], dict_converter=Object.fromEntries)
|
|
95
|
+
js_options = to_js({k: v for k, v in options.items() if v is not None}, dict_converter=Object.fromEntries)
|
|
96
|
+
return _node(_wait(bridge.call(name, js_args, js_options)))
|
|
97
|
+
|
|
98
|
+
# Above 0 while a function passed to `pie.lift` runs. It can't reach the page: a rerun runs outside any block.
|
|
99
|
+
_lift_depth = 0
|
|
100
|
+
|
|
101
|
+
def _check_bridge():
|
|
102
|
+
if _lift_depth:
|
|
103
|
+
raise RuntimeError("pie.* calls and array indexing aren't allowed inside a function passed to pie.lift")
|
|
104
|
+
|
|
105
|
+
# Type passed to `pie.lift` -> (kind, item type).
|
|
106
|
+
_RETURNS = [
|
|
107
|
+
(Scalar, ("Scalar", None)),
|
|
108
|
+
(Point, ("Point", None)),
|
|
109
|
+
(Text, ("Text", None)),
|
|
110
|
+
(str, ("Text", None)),
|
|
111
|
+
(Array[Scalar], ("Array", "Scalar")),
|
|
112
|
+
(Array[Point], ("Array", "Point")),
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
class _Slot:
|
|
116
|
+
"""Where node argument `index` goes in a stored call."""
|
|
117
|
+
def __init__(self, index):
|
|
118
|
+
self.index = index
|
|
119
|
+
|
|
120
|
+
def lift(fn, out_type):
|
|
121
|
+
"""
|
|
122
|
+
A regular Python function `fn` can be _lifted_ to accept nodes (Scalar, Point, Text and Array)
|
|
123
|
+
g = pie.lift(fn, out_type)
|
|
124
|
+
- If `fn` returns a num, `g` returns `Scalar`, out_type = `Scalar`
|
|
125
|
+
- If `fn` returns a tuple or array of len 2, `g` returns `Point`, out_type = `Point`
|
|
126
|
+
- If `fn` returns a str, `g` returns `Text`, out_type = `Text` or `str`
|
|
127
|
+
- If `fn` returns a numpy array, `g` can return `Array[Point]` or `Array[Scalar]`
|
|
128
|
+
"""
|
|
129
|
+
returns = next((r for t, r in _RETURNS if out_type == t), None)
|
|
130
|
+
if returns is None:
|
|
131
|
+
raise TypeError(f"pie.lift: out_type must be pie.Scalar, pie.Point, pie.Text (or str), pie.Array[pie.Scalar] or pie.Array[pie.Point], got {out_type!r}")
|
|
132
|
+
# The page's globals: `lift` is called from a block.
|
|
133
|
+
scope = sys._getframe(1).f_globals
|
|
134
|
+
name = getattr(fn, "__name__", None)
|
|
135
|
+
# A function defined in a block is found by name, so a later `def f` is used. Anything else, e.g. np.linspace, by reference.
|
|
136
|
+
target = name if name is not None and scope.get(name) is fn else fn
|
|
137
|
+
label = name or repr(fn)
|
|
138
|
+
|
|
139
|
+
def lifted(*args, out=None, hidden=False, fill=None, stroke=None, **kwargs):
|
|
140
|
+
return _lifted_node(scope, target, label, returns, args, kwargs, out, hidden, fill, stroke)
|
|
141
|
+
lifted.__name__ = lifted.__qualname__ = f"lift({label})"
|
|
142
|
+
return lifted
|
|
143
|
+
|
|
144
|
+
def _lifted_node(scope, target, label, returns, args, kwargs, out, hidden, fill, stroke):
|
|
145
|
+
_check_bridge()
|
|
146
|
+
ids = []
|
|
147
|
+
def slot(a):
|
|
148
|
+
if not isinstance(a, Node):
|
|
149
|
+
return a
|
|
150
|
+
ids.append(a.id)
|
|
151
|
+
return _Slot(len(ids) - 1)
|
|
152
|
+
# The call, with node arguments as slots. Reruns fill the slots with new values; other arguments stay as they are.
|
|
153
|
+
call = (target, label, [slot(a) for a in args], {k: slot(v) for k, v in kwargs.items()}, returns)
|
|
154
|
+
kind, item = returns
|
|
155
|
+
reply = run_sync(bridge.lift(label, to_js(ids), kind, out, fill, stroke))
|
|
156
|
+
shape, values = _evaluate(scope, call, reply.values.to_py())
|
|
157
|
+
save = {"id": reply.id, "name": label, "inputIds": ids, "kind": kind, "itemType": item, "shape": shape, "values": values, "hidden": hidden, "fill": fill, "stroke": stroke}
|
|
158
|
+
bridge.lift_save(to_js(save, dict_converter=Object.fromEntries))
|
|
159
|
+
scope.setdefault("__pie_lift__", {})[reply.id] = call
|
|
160
|
+
if kind == "Array":
|
|
161
|
+
return Array(reply.id, tuple(shape), item)
|
|
162
|
+
return {"Scalar": Scalar, "Point": Point, "Text": Text}[kind](reply.id)
|
|
163
|
+
|
|
164
|
+
def _rerun(scope, node_id, values):
|
|
165
|
+
"""Called by the worker when an input of node `node_id` changes. `values`: the input values, in slot order."""
|
|
166
|
+
call = scope.get("__pie_lift__", {}).get(node_id)
|
|
167
|
+
if call is None:
|
|
168
|
+
raise RuntimeError("Python was restarted, so this node can't rerun. Run the block that made it again.")
|
|
169
|
+
shape, values = _evaluate(scope, call, values)
|
|
170
|
+
return {"shape": shape, "values": values}
|
|
171
|
+
|
|
172
|
+
# The running block's globals. The worker sets it before each run, so a batch can find lifted functions.
|
|
173
|
+
_scope = None
|
|
174
|
+
|
|
175
|
+
def _wait(request):
|
|
176
|
+
"""
|
|
177
|
+
Waits for the page's reply to `request`. Before an animation, the reply can be a batch instead: the lifted
|
|
178
|
+
functions to run for its steps. Then runs them, sends the results, and waits for the next reply.
|
|
179
|
+
"""
|
|
180
|
+
reply = run_sync(request)
|
|
181
|
+
while (batch := getattr(reply, "batch", None)) is not None:
|
|
182
|
+
reply = run_sync(bridge.batch_done(to_js(_run_batch(batch), dict_converter=Object.fromEntries)))
|
|
183
|
+
return reply
|
|
184
|
+
|
|
185
|
+
def _run_batch(batch):
|
|
186
|
+
"""Each job's lifted function, once per entry of its inputs. A failure gives {"error": message} for that entry."""
|
|
187
|
+
return [[_try_rerun(job.nodeId, values) for values in job.inputs.to_py()] for job in batch]
|
|
188
|
+
|
|
189
|
+
def _try_rerun(node_id, values):
|
|
190
|
+
try:
|
|
191
|
+
return _rerun(_scope, node_id, values)
|
|
192
|
+
except Exception as e:
|
|
193
|
+
return {"error": f"{type(e).__name__}: {e}"}
|
|
194
|
+
|
|
195
|
+
def _evaluate(scope, call, values):
|
|
196
|
+
"""Calls the function: by name, the one now named so in `scope`; otherwise the one kept."""
|
|
197
|
+
global _lift_depth
|
|
198
|
+
target, label, args, kwargs, returns = call
|
|
199
|
+
if isinstance(target, str):
|
|
200
|
+
if target not in scope:
|
|
201
|
+
raise NameError(f"name '{target}' is not defined")
|
|
202
|
+
fn = scope[target]
|
|
203
|
+
else:
|
|
204
|
+
fn = target
|
|
205
|
+
# A Scalar's value arrives as a number, a Point's as [x, y], a Text's as a str, an Array's as {shape, values}.
|
|
206
|
+
def fill(a):
|
|
207
|
+
if not isinstance(a, _Slot):
|
|
208
|
+
return a
|
|
209
|
+
v = values[a.index]
|
|
210
|
+
if isinstance(v, str):
|
|
211
|
+
return v
|
|
212
|
+
if isinstance(v, dict):
|
|
213
|
+
import numpy as np
|
|
214
|
+
return np.array(v["values"]).reshape(v["shape"])
|
|
215
|
+
return tuple(float(c) for c in v) if isinstance(v, list) else float(v)
|
|
216
|
+
_lift_depth += 1
|
|
217
|
+
try:
|
|
218
|
+
result = fn(*map(fill, args), **{k: fill(v) for k, v in kwargs.items()})
|
|
219
|
+
finally:
|
|
220
|
+
_lift_depth -= 1
|
|
221
|
+
return _check_out_type_and_flatten(label, returns, result)
|
|
222
|
+
|
|
223
|
+
def _is_number(v):
|
|
224
|
+
return isinstance(v, numbers.Real)
|
|
225
|
+
|
|
226
|
+
def _check_out_type_and_flatten(name, returns, result):
|
|
227
|
+
"""`result` as (shape, values): every number in row-major order, a Point as x, y. A Text's values: [the string]."""
|
|
228
|
+
kind, item = returns
|
|
229
|
+
if kind == "Text":
|
|
230
|
+
if not isinstance(result, str):
|
|
231
|
+
raise TypeError(f"{name} is lifted to pie.Text, so it must return a str, got {type(result).__name__}")
|
|
232
|
+
return [], [result]
|
|
233
|
+
if kind == "Scalar":
|
|
234
|
+
if not _is_number(result):
|
|
235
|
+
raise TypeError(f"{name} is lifted to pie.Scalar, so it must return a number, got {type(result).__name__}")
|
|
236
|
+
return [], [float(result)]
|
|
237
|
+
if kind == "Point":
|
|
238
|
+
if not (isinstance(result, (tuple, list)) and len(result) == 2 and all(map(_is_number, result))):
|
|
239
|
+
raise TypeError(f"{name} is lifted to pie.Point, so it must return a tuple or list of 2 numbers, got {type(result).__name__}")
|
|
240
|
+
return [], [float(c) for c in result]
|
|
241
|
+
lifted_to = f"lifted to pie.Array[pie.{item}]"
|
|
242
|
+
np = sys.modules.get("numpy")
|
|
243
|
+
if np is None or not isinstance(result, np.ndarray):
|
|
244
|
+
raise TypeError(f"{name} is {lifted_to}, so it must return a numpy array, got {type(result).__name__}")
|
|
245
|
+
if result.dtype.kind not in "biuf":
|
|
246
|
+
raise TypeError(f"{name} is {lifted_to}, so its array must hold numbers, got dtype {result.dtype}")
|
|
247
|
+
if item == "Point" and (result.ndim < 2 or result.shape[-1] != 2):
|
|
248
|
+
raise ValueError(f"{name} is {lifted_to}, so its array's shape must end in 2, with at least 2 dimensions, got {result.shape}")
|
|
249
|
+
if result.ndim < 1:
|
|
250
|
+
raise ValueError(f"{name} is {lifted_to}, so its array needs at least 1 dimension, got shape {result.shape}")
|
|
251
|
+
if result.size == 0:
|
|
252
|
+
raise ValueError(f"{name} returned an empty array, shape {result.shape}")
|
|
253
|
+
shape = result.shape[:-1] if item == "Point" else result.shape
|
|
254
|
+
return list(shape), result.astype(np.float64).ravel().tolist()
|
|
255
|
+
|
|
256
|
+
class _UI:
|
|
257
|
+
"""
|
|
258
|
+
`pie.ui.<name>(*nodes, **options)` shows UI `<name>` for the nodes below the block. A rerun of the block replaces it.
|
|
259
|
+
Every UI takes `label`, text shown in front of it (default: none).
|
|
260
|
+
"""
|
|
261
|
+
def __getattr__(self, name):
|
|
262
|
+
if name.startswith("_"):
|
|
263
|
+
raise AttributeError(name)
|
|
264
|
+
def show(*args, **options):
|
|
265
|
+
_show_ui(name, args, options)
|
|
266
|
+
show.__name__ = show.__qualname__ = f"ui.{name}"
|
|
267
|
+
return show
|
|
268
|
+
|
|
269
|
+
ui = _UI()
|
|
270
|
+
|
|
271
|
+
def _ui_arg(name, a):
|
|
272
|
+
if isinstance(a, Node):
|
|
273
|
+
return {"id": a.id}
|
|
274
|
+
if isinstance(a, (list, tuple)):
|
|
275
|
+
return [_ui_arg(name, x) for x in a]
|
|
276
|
+
raise TypeError(f"pie.ui.{name}: positional arguments must be nodes or lists of nodes, got {type(a).__name__}")
|
|
277
|
+
|
|
278
|
+
def _holds_node(v):
|
|
279
|
+
if isinstance(v, Node):
|
|
280
|
+
return True
|
|
281
|
+
if isinstance(v, (list, tuple)):
|
|
282
|
+
return any(map(_holds_node, v))
|
|
283
|
+
if isinstance(v, dict):
|
|
284
|
+
return any(map(_holds_node, v.values()))
|
|
285
|
+
return False
|
|
286
|
+
|
|
287
|
+
def _show_ui(name, args, options):
|
|
288
|
+
_check_bridge()
|
|
289
|
+
if "args" in options:
|
|
290
|
+
raise TypeError(f"pie.ui.{name}: 'args' can't be a keyword argument")
|
|
291
|
+
for key, value in options.items():
|
|
292
|
+
if _holds_node(value):
|
|
293
|
+
raise TypeError(f"pie.ui.{name}: keyword argument '{key}' holds a node; pass nodes as positional arguments")
|
|
294
|
+
js_args = to_js([_ui_arg(name, a) for a in args], dict_converter=Object.fromEntries)
|
|
295
|
+
js_options = to_js(options, dict_converter=Object.fromEntries)
|
|
296
|
+
run_sync(bridge.ui(name, js_args, js_options))
|
|
297
|
+
|
|
298
|
+
def __getattr__(name):
|
|
299
|
+
if name.startswith("_"):
|
|
300
|
+
raise AttributeError(name)
|
|
301
|
+
def fn(*args, out=None, hidden=None, fill=None, stroke=None, animate=None):
|
|
302
|
+
return _call(name, args, out=out, hidden=hidden, fill=fill, stroke=stroke, animate=animate)
|
|
303
|
+
return fn
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Matplotlib backend: `plt.show()` sends each open figure to the editor as a PNG, then closes it.
|
|
2
|
+
import base64, io, sys
|
|
3
|
+
import bridge
|
|
4
|
+
from matplotlib._pylab_helpers import Gcf
|
|
5
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
|
|
6
|
+
|
|
7
|
+
def show(*args, **kwargs):
|
|
8
|
+
# Text printed before the plot must reach the editor first.
|
|
9
|
+
sys.stdout.flush()
|
|
10
|
+
sys.stderr.flush()
|
|
11
|
+
for manager in Gcf.get_all_fig_managers():
|
|
12
|
+
buf = io.BytesIO()
|
|
13
|
+
manager.canvas.figure.savefig(buf, format="png")
|
|
14
|
+
bridge.plot(base64.b64encode(buf.getvalue()).decode())
|
|
15
|
+
Gcf.destroy_all()
|