diff --git a/pathview/converter.py b/pathview/converter.py index eff2e741..698fcffd 100644 --- a/pathview/converter.py +++ b/pathview/converter.py @@ -71,7 +71,7 @@ def generate_param_string(params: dict, valid_params: set[str], multi_line: bool def with_port_structure(node: dict, registry: dict) -> dict: - """Fill the pathsim key and the carrier channels of the fixed ports of a + """Fill the pathsim key and the carrier channels of the labeled ports of a node from the registry, by index, recursing into subsystems. For files saved before ports carried their structure: the saved names are display names (e.g. "out 0" for the label "out") and do not tell the key. Ports diff --git a/pathview/data/registry.json b/pathview/data/registry.json index b5a054b2..150e3ed9 100644 --- a/pathview/data/registry.json +++ b/pathview/data/registry.json @@ -646,7 +646,9 @@ "inputs": [ "in" ], - "outputs": null + "outputs": [ + "out_0" + ] }, "LUT": { "blockClass": "LUT", diff --git a/scripts/extract.py b/scripts/extract.py index 345ca396..d56ba858 100644 --- a/scripts/extract.py +++ b/scripts/extract.py @@ -253,8 +253,9 @@ def _extract_block(self, cls, config: dict) -> dict: "inputs": block["inputs"], "outputs": block["outputs"], "icon": block["icon"], - #only for blocks with carrier ports, the file stays as it was otherwise - **{key: block[key] for key in ("inputBuses", "outputBuses") if block[key]}, + #only for blocks with carrier ports or parameter dependent ports, + #the file stays as it was otherwise + **{key: block[key] for key in ("inputBuses", "outputBuses", "portParameters") if block[key]}, } def _import_module(self, import_path: str) -> Any: @@ -632,6 +633,7 @@ def write_blocks(self, blocks: dict, config: dict, import_paths: dict[str, str] " icon: string | null; // SVG icon from Block.icon(), null if the block has none", " inputBuses?: Record; // signals of the ports that are carriers, by name", " outputBuses?: Record;", + " portParameters?: string[]; // parameters the ports depend on, the ports above are those of the defaults", "}", "", "export const extractedBlocks: Record = ", diff --git a/scripts/generated/registry.json b/scripts/generated/registry.json index b5a054b2..150e3ed9 100644 --- a/scripts/generated/registry.json +++ b/scripts/generated/registry.json @@ -646,7 +646,9 @@ "inputs": [ "in" ], - "outputs": null + "outputs": [ + "out_0" + ] }, "LUT": { "blockClass": "LUT", diff --git a/scripts/pathview_introspect.py b/scripts/pathview_introspect.py index 244eb796..2048296d 100644 --- a/scripts/pathview_introspect.py +++ b/scripts/pathview_introspect.py @@ -207,6 +207,27 @@ def process_port_buses(labels): } +def process_ports(input_labels, output_labels): + """Ports of a block from its input and output port labels, in the shape + the editor reads: the port names and the channels of carrier ports.""" + return { + "inputs": process_port_labels(input_labels), + "outputs": process_port_labels(output_labels), + "inputBuses": process_port_buses(input_labels), + "outputBuses": process_port_buses(output_labels), + } + + +def instance_ports(block): + """Ports of a block instance, which differ from those of its class for + blocks whose ports depend on their parameters (`port_parameters`). + None for a pathsim whose `info()` does not report instances.""" + info = block.info() + if "port_parameters" not in info: + return None + return process_ports(info.get("input_port_labels"), info.get("output_port_labels")) + + # --- Class detection (runtime needs heuristics) -------------------------- @@ -267,6 +288,19 @@ def extract_block(cls): if info is not None: rst = (info.get("description") or raw_doc).strip() + + #blocks whose ports depend on their parameters start with the ports + #of an instance with the default parameters + port_parameters = list(info.get("port_parameters") or ()) + ports = None + if port_parameters: + try: + ports = instance_ports(cls()) + except Exception: + ports = None + if ports is None: + ports = process_ports(info.get("input_port_labels"), info.get("output_port_labels")) + params = [] for pname, meta in (info.get("parameters") or {}).items(): default = meta.get("default") if isinstance(meta, dict) else None @@ -280,10 +314,8 @@ def extract_block(cls): "className": cls.__name__, "description": first_line(rst), "docstringHtml": rst_to_html(rst), - "inputs": process_port_labels(info.get("input_port_labels")), - "outputs": process_port_labels(info.get("output_port_labels")), - "inputBuses": process_port_buses(info.get("input_port_labels")), - "outputBuses": process_port_buses(info.get("output_port_labels")), + **ports, + "portParameters": port_parameters, "params": params, "icon": block_icon(cls), } @@ -293,10 +325,8 @@ def extract_block(cls): "className": cls.__name__, "description": first_line(raw_doc), "docstringHtml": rst_to_html(raw_doc), - "inputs": process_port_labels(getattr(cls, "input_port_labels", None)), - "outputs": process_port_labels(getattr(cls, "output_port_labels", None)), - "inputBuses": process_port_buses(getattr(cls, "input_port_labels", None)), - "outputBuses": process_port_buses(getattr(cls, "output_port_labels", None)), + **process_ports(getattr(cls, "input_port_labels", None), getattr(cls, "output_port_labels", None)), + "portParameters": [], "params": extract_params_from_signature(cls, raw_doc), "icon": block_icon(cls), } diff --git a/src/lib/nodes/defineNode.ts b/src/lib/nodes/defineNode.ts index ddb0a922..f7e45f8d 100644 --- a/src/lib/nodes/defineNode.ts +++ b/src/lib/nodes/defineNode.ts @@ -28,6 +28,8 @@ interface DefineNodeOptions { minOutputs?: number; inputPolicy?: PortPolicy; // default 'variable' outputPolicy?: PortPolicy; + /** Parameters the ports depend on, for 'derived' ports */ + portParameters?: string[]; syncPorts?: boolean; // When true, output count always equals input count // Shape override (defaults based on category) @@ -49,10 +51,15 @@ interface DefineNodeOptions { /** * Ports of a pathsim block in one direction from its introspected port labels: - * a list gives fixed ports named by their labels, `null` variable ports + * a list gives ports named by their labels, fixed, or derived for a block whose + * ports depend on its parameters, `null` variable ports */ -export function portsFromLabels(labels: string[] | null | undefined): { names: string[] | undefined; policy: PortPolicy } { - return labels == null ? { names: undefined, policy: 'variable' } : { names: labels, policy: 'fixed' }; +export function portsFromLabels( + labels: string[] | null | undefined, + portParameters?: string[] +): { names: string[] | undefined; policy: PortPolicy } { + if (labels == null) return { names: undefined, policy: 'variable' }; + return { names: labels, policy: portParameters?.length ? 'derived' : 'fixed' }; } /** @@ -74,6 +81,7 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition { minOutputs = 1, inputPolicy = 'variable', outputPolicy = 'variable', + portParameters, syncPorts, shape, params = {} @@ -104,14 +112,14 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition { name: portName, direction: 'input' as const, color: PORT_COLORS.default, - ...(labeled && inputPolicy === 'fixed' ? { key: portName } : {}), + ...(labeled && inputPolicy !== 'variable' ? { key: portName } : {}), ...(inputBuses[portName] ? { bus: inputBuses[portName] } : {}) })), outputs: outputs.map((portName) => ({ name: portName, direction: 'output' as const, color: PORT_COLORS.default, - ...(labeled && outputPolicy === 'fixed' ? { key: portName } : {}), + ...(labeled && outputPolicy !== 'variable' ? { key: portName } : {}), ...(outputBuses[portName] ? { bus: outputBuses[portName] } : {}) })), minInputs, @@ -121,6 +129,7 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition { syncPorts }, - params: paramDefs + params: paramDefs, + ...(portParameters?.length ? { portParameters } : {}) }; } diff --git a/src/lib/nodes/generated/blocks.ts b/src/lib/nodes/generated/blocks.ts index 209a0282..19707400 100644 --- a/src/lib/nodes/generated/blocks.ts +++ b/src/lib/nodes/generated/blocks.ts @@ -22,26 +22,30 @@ export interface ExtractedBlock { icon: string | null; // SVG icon from Block.icon(), null if the block has none inputBuses?: Record; // signals of the ports that are carriers, by name outputBuses?: Record; + portParameters?: string[]; // parameters the ports depend on, the ports above are those of the defaults } export const extractedBlocks: Record = { "Constant": { "blockClass": "Constant", - "description": "Produces a constant output signal (SISO).", - "docstringHtml": "

Produces a constant output signal (SISO).

\n
\n\\begin{equation*}\ny(t) = const.\n\\end{equation*}\n
\n
\n

Parameters

\n
\n
value : float
\n
constant defining block output
\n
\n
\n", + "description": "Produces a constant output signal.", + "docstringHtml": "

Produces a constant output signal.

\n
\n\\begin{equation*}\ny(t) = const.\n\\end{equation*}\n
\n

A scalar value gives a single output 'out', an array value one output\nper element, 'out_0', 'out_1', ...

\n
\n

Example

\n

Constant boundary values for three channels, for example the inlet flows\nof a stream that is a carrier input of the block 'B':

\n
\nC = Constant([1.0, 0.5, 0.0])\n\nCon = Connection(C[0:3], B["in"])\n
\n
\n
\n

Parameters

\n
\n
value : float, array_like
\n
constant defining block output, scalar or 1d array
\n
\n
\n", "params": { "value": { "type": "integer", "default": "1", - "description": "constant defining block output" + "description": "constant defining block output, scalar or 1d array" } }, "inputs": [], "outputs": [ "out" ], - "icon": "\n" + "icon": "\n", + "portParameters": [ + "value" + ] }, "Source": { "blockClass": "Source", @@ -1243,8 +1247,13 @@ export const extractedBlocks: Record = "inputs": [ "in" ], - "outputs": null, - "icon": "\n \n \n \n\n" + "outputs": [ + "out_0" + ], + "icon": "\n \n \n \n\n", + "portParameters": [ + "fractions" + ] }, "LUT": { "blockClass": "LUT", diff --git a/src/lib/nodes/ports.ts b/src/lib/nodes/ports.ts index 575a7e89..6f6513a8 100644 --- a/src/lib/nodes/ports.ts +++ b/src/lib/nodes/ports.ts @@ -15,11 +15,12 @@ export function nodePort(node: NodeInstance, direction: PortDirection, index: nu } /** - * Fill the pathsim key and the carrier channels of the fixed ports of a node - * from its type definition, by index, recursing into subsystems. For nodes - * saved before ports carried their structure: the saved names are display - * names (e.g. "out 0" for the label "out") and do not tell the key. Ports that - * have a key, variable ports and unknown types are left as they are. + * Fill the pathsim key and the carrier channels of the labeled ports of a node + * (fixed, or derived with the ports of the default parameters) from its type + * definition, by index, recursing into subsystems. For nodes saved before ports + * carried their structure: the saved names are display names (e.g. "out 0" for + * the label "out") and do not tell the key. Ports that have a key, variable + * ports and unknown types are left as they are. */ export function withPortStructure(node: NodeInstance): NodeInstance { let result = node; @@ -28,7 +29,7 @@ export function withPortStructure(node: NodeInstance): NodeInstance { for (const direction of ['input', 'output'] as const) { const portsKey = direction === 'input' ? 'inputs' : 'outputs'; const policy = direction === 'input' ? typeDef.ports.inputPolicy : typeDef.ports.outputPolicy; - if (policy !== 'fixed') continue; + if (policy === 'variable') continue; const defs = typeDef.ports[portsKey]; const ports = result[portsKey]; if (!ports.some((port, i) => port.key === undefined && (defs[i]?.key !== undefined || defs[i]?.bus))) continue; diff --git a/src/lib/nodes/registry.ts b/src/lib/nodes/registry.ts index d3bced0c..8096b55c 100644 --- a/src/lib/nodes/registry.ts +++ b/src/lib/nodes/registry.ts @@ -177,8 +177,8 @@ function createNodeFromExtracted( }; } - const inputs = portsFromLabels(extracted.inputs); - const outputs = portsFromLabels(extracted.outputs); + const inputs = portsFromLabels(extracted.inputs, extracted.portParameters); + const outputs = portsFromLabels(extracted.outputs, extracted.portParameters); const definition = defineNode({ name, @@ -192,6 +192,7 @@ function createNodeFromExtracted( outputBuses: extracted.outputBuses, inputPolicy: inputs.policy, outputPolicy: outputs.policy, + portParameters: extracted.portParameters, syncPorts: syncPortBlocks.has(name), params }); diff --git a/src/lib/pyodide/codeBuilder.ts b/src/lib/pyodide/codeBuilder.ts index 00cb70b5..528560e5 100644 --- a/src/lib/pyodide/codeBuilder.ts +++ b/src/lib/pyodide/codeBuilder.ts @@ -5,6 +5,9 @@ import type { NodeInstance, PortDirection } from '$lib/nodes/types'; import { nodePort } from '$lib/nodes/ports'; +import { nodeRegistry } from '$lib/nodes/registry'; +import { blockImportPaths } from '$lib/nodes/generated/blocks'; +import { enginePath } from '$lib/constants/engine'; import type { ExpandedConnection } from '$lib/bus/expand'; /** Options for parameter string generation */ @@ -53,6 +56,16 @@ export function generateParamString( return parts.join(', '); } +/** + * Module a block class is imported from: toolbox blocks carry their own + * import path, built-ins come from the static map, else core pathsim.blocks. + * enginePath() rewrites core pathsim paths to the active engine module + * (identity in the default pathsim build). + */ +export function blockImportPath(blockClass: string): string { + return enginePath(nodeRegistry.get(blockClass)?.importPath ?? blockImportPaths[blockClass] ?? 'pathsim.blocks'); +} + /** * Key of a block port in pathsim: the label the port carries, for the fixed * ports of a pathsim block, else its index. Labeled ports go by label because diff --git a/src/lib/pyodide/pathsimRunner.ts b/src/lib/pyodide/pathsimRunner.ts index 0f893a56..86b31ffa 100644 --- a/src/lib/pyodide/pathsimRunner.ts +++ b/src/lib/pyodide/pathsimRunner.ts @@ -11,8 +11,7 @@ import { eventRegistry } from '$lib/events/registry'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; import { BLOCK_CATEGORY_ORDER } from '$lib/constants/python'; import { isSubsystem, isInterface } from '$lib/nodes/shapes'; -import { blockImportPaths } from '$lib/nodes/generated/blocks'; -import { ENGINE_MODULE, enginePath } from '$lib/constants/engine'; +import { ENGINE_MODULE } from '$lib/constants/engine'; import { generateEngineSetup } from './engineCodegen'; import { graphStore, findParentSubsystem } from '$lib/stores/graph'; import { expandBuses, isBusBlock } from '$lib/bus/expand'; @@ -26,7 +25,8 @@ import { generateParamString, generateNamedConnections, generateListDefinition, - sanitizeName + sanitizeName, + blockImportPath } from './codeBuilder'; // Re-export sanitizeName for external use @@ -165,13 +165,7 @@ function collectBlockImportGroups(nodes: NodeInstance[]): Map + ({ id, type, name: id, params: {}, position: { x: 0, y: 0 }, inputs, outputs }) as NodeInstance; +const wire = (source: string, sourcePort: number, target: string, targetPort: number): Connection => ({ + id: `${source}:${sourcePort}-${target}:${targetPort}`, + sourceNodeId: source, + sourcePortIndex: sourcePort, + targetNodeId: target, + targetPortIndex: targetPort +}); +const labeled = (nodeId: string, direction: 'input' | 'output', labels: string[]) => + createPorts(nodeId, direction, labels.map((label) => ({ name: label, key: label }))); + +/** A Splitter with outputs out_0, out_1 wired to two scopes, the second output renamed */ +function splitter(outputs = labeled('sp', 'output', ['out_0', 'out_1'])) { + outputs[1] = { ...outputs[1], name: 'bypass' }; + graphStore.fromJSON( + [ + node('sp', 'Splitter', labeled('sp', 'input', ['in']), outputs), + node('a', 'Scope', createPorts('a', 'input', [{ name: 'in 0' }]), []), + node('b', 'Scope', createPorts('b', 'input', [{ name: 'in 0' }]), []) + ], + [wire('sp', 0, 'a', 0), wire('sp', 1, 'b', 0)] + ); +} +const level = () => graphAt([]); +const sp = () => level().nodes.find((n) => n.id === 'sp')!; + +describe('derived ports', () => { + it('adds the ports the block reports and keeps the names and wires of the others', () => { + splitter(); + graphStore.setDerivedPorts([], 'sp', { inputs: ['in'], outputs: ['out_0', 'out_1', 'out_2'] }); + expect(sp().outputs.map((p) => [p.key, p.name])).toEqual([ + ['out_0', 'out_0'], + ['out_1', 'bypass'], + ['out_2', 'out_2'] + ]); + expect(level().connections.map((c) => c.sourcePortIndex)).toEqual([0, 1]); + }); + + it('removes the wires of ports the block no longer has', () => { + splitter(); + graphStore.setDerivedPorts([], 'sp', { inputs: ['in'], outputs: ['out_0'] }); + expect(sp().outputs.map((p) => p.key)).toEqual(['out_0']); + expect(level().connections.map((c) => c.targetNodeId)).toEqual(['a']); + }); + + it('moves wires with their port when its index changes', () => { + splitter(); + graphStore.setDerivedPorts([], 'sp', { inputs: ['in'], outputs: ['out_1'] }); + expect(sp().outputs[0].name).toBe('bypass'); + expect(level().connections).toEqual([{ ...wire('sp', 1, 'b', 0), sourcePortIndex: 0 }]); + }); + + it('matches ports saved without key by index', () => { + splitter(createPorts('sp', 'output', [{ name: 'out 0' }, { name: 'out 1' }])); + graphStore.setDerivedPorts([], 'sp', { inputs: ['in'], outputs: ['out_0', 'out_1'] }); + expect(sp().outputs.map((p) => [p.key, p.name])).toEqual([ + ['out_0', 'out 0'], + ['out_1', 'bypass'] + ]); + expect(level().connections).toHaveLength(2); + }); +}); diff --git a/src/lib/stores/graph/derivedPorts.ts b/src/lib/stores/graph/derivedPorts.ts new file mode 100644 index 00000000..e472ba54 --- /dev/null +++ b/src/lib/stores/graph/derivedPorts.ts @@ -0,0 +1,50 @@ +/** + * Graph store - Derived ports + * + * The ports of a block whose ports depend on its parameters (`portParameters` + * of its type) come from the pathsim block built with the parameters of the + * node, when one of them is committed. + */ + +import { get } from 'svelte/store'; +import type { NodeInstance } from '$lib/nodes/types'; +import { nodeRegistry } from '$lib/nodes/registry'; +import { generateParamString, blockImportPath } from '$lib/pyodide/codeBuilder'; +import { introspectBlockPorts } from '$lib/toolbox/installer'; +import { codeContextStore } from '$lib/stores/codeContext'; +import { consoleStore } from '$lib/stores/console'; +import { currentPath, graphAt } from './state'; +import { setDerivedPorts } from './ports'; + +/** Constructor arguments of the block of a node, as in the generated code */ +function constructorArgs(node: NodeInstance): string { + const typeDef = nodeRegistry.get(node.type); + return generateParamString(node.params, new Set(typeDef?.params.map((p) => p.name)), { skipInternal: true }); +} + +/** Derive the ports of a node at the current level, if they depend on one of the changed parameters */ +export function deriveChangedPorts(nodeId: string, changedParams: string[]): void { + const path = get(currentPath); + const node = graphAt(path).nodes.find((n) => n.id === nodeId); + const portParameters = node && nodeRegistry.get(node.type)?.portParameters; + if (portParameters?.some((p) => changedParams.includes(p))) void derivePorts(path, nodeId); +} + +async function derivePorts(path: string[], nodeId: string): Promise { + const node = graphAt(path).nodes.find((n) => n.id === nodeId); + const typeDef = node && nodeRegistry.get(node.type); + if (!node || !typeDef) return; + + const args = constructorArgs(node); + try { + const ports = await introspectBlockPorts(blockImportPath(typeDef.blockClass), typeDef.blockClass, args, codeContextStore.getCode()); + + //parameters edited while Python ran: a later derivation follows + const current = graphAt(path).nodes.find((n) => n.id === nodeId); + if (!current || constructorArgs(current) !== args) return; + + setDerivedPorts(path, nodeId, ports); + } catch (e) { + consoleStore.warn(`[ports] ${node.name}: ports kept, ${e instanceof Error ? e.message : String(e)}`); + } +} diff --git a/src/lib/stores/graph/index.ts b/src/lib/stores/graph/index.ts index efb26321..2c5a1103 100644 --- a/src/lib/stores/graph/index.ts +++ b/src/lib/stores/graph/index.ts @@ -87,6 +87,7 @@ export const graphStore = { addOutputPort: ports.addOutputPort, removeOutputPort: ports.removeOutputPort, updateNodePortName: ports.updateNodePortName, + setDerivedPorts: ports.setDerivedPorts, // ==================== ANNOTATION OPERATIONS ==================== addAnnotation: annotations.addAnnotation, diff --git a/src/lib/stores/graph/nodes.ts b/src/lib/stores/graph/nodes.ts index 6bfb0f14..6c5ee755 100644 --- a/src/lib/stores/graph/nodes.ts +++ b/src/lib/stores/graph/nodes.ts @@ -27,6 +27,7 @@ import { syncPortNamesFromLabels } from './ports'; import { triggerSelectNodes } from '$lib/stores/viewActions'; import { getPortLabelConfigs } from '$lib/nodes/uiConfig'; import { queueAddBlock, queueRemoveBlock, queueAddConnection, queueRemoveConnection, queueUpdateParam } from '$lib/pyodide/mutationQueue'; +import { deriveChangedPorts } from './derivedPorts'; /** * Add a new node to the current graph context @@ -225,6 +226,9 @@ export function updateNodeParams(id: string, params: Record): v queueUpdateParam(id, paramName, String(value)); } + // Derive the ports of blocks whose ports depend on their parameters + deriveChangedPorts(id, Object.keys(params)); + // Sync port names if this block has label-driven ports const node = getCurrentGraph().nodes.get(id); if (node) { diff --git a/src/lib/stores/graph/ports.ts b/src/lib/stores/graph/ports.ts index 193053ec..c1c685cd 100644 --- a/src/lib/stores/graph/ports.ts +++ b/src/lib/stores/graph/ports.ts @@ -3,7 +3,7 @@ */ import { get } from 'svelte/store'; -import type { NodeInstance, PortInstance } from '$lib/nodes/types'; +import type { NodeInstance, PortInstance, Connection } from '$lib/nodes/types'; import { nodeRegistry } from '$lib/nodes/registry'; import { getPortLabelConfigs } from '$lib/nodes/uiConfig'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; @@ -15,9 +15,13 @@ import { getCurrentGraph, updateSubsystemGraph, updateNodeById, - updateCurrentNodesAndConnections + updateCurrentNodesAndConnections, + graphAt, + updateNodesAndConnectionsAt } from './state'; import { queueRemoveConnection } from '$lib/pyodide/mutationQueue'; +import type { IntrospectedPorts } from '$lib/toolbox/installer'; +import { createPorts } from './helpers'; type PortDirection = 'input' | 'output'; @@ -221,6 +225,73 @@ function removePort(nodeId: string, direction: PortDirection, syncFollowUp = fal return true; } +/** + * Set the derived ports of a node (see the 'derived' port policy) from the + * ports its pathsim block reports. A port keeps the display name and color of + * the port it had with the same key, or at the same index for a port saved + * without key. Connections follow their port to its new index, connections to + * ports the block no longer has are removed, also from a running simulation. + * + * @param path - Subsystem path of the level the node is at, it need not be shown + */ +export function setDerivedPorts(path: string[], nodeId: string, ports: IntrospectedPorts): void { + const level = graphAt(path); + const node = level.nodes.find((n) => n.id === nodeId); + if (!node) return; + + /** Index of the old port among the new ports, null if it is gone */ + const matches = (old: PortInstance[], next: PortInstance[]) => + old.map((port, index) => { + const i = port.key !== undefined ? next.findIndex((p) => p.key === port.key) : index < next.length ? index : -1; + return i < 0 ? null : i; + }); + + const derive = (direction: PortDirection) => { + const config = getPortConfig(direction); + const labels = (direction === 'input' ? ports.inputs : ports.outputs) ?? []; + const buses = (direction === 'input' ? ports.inputBuses : ports.outputBuses) ?? {}; + const old = node[config.portsKey] as PortInstance[]; + const next = createPorts(nodeId, direction, labels.map((label) => ({ name: label, key: label, bus: buses[label] }))); + const index = matches(old, next); + index.forEach((i, j) => { + if (i !== null) next[i] = { ...next[i], name: old[j].name, color: old[j].color }; + }); + return { ports: next, index }; + }; + const inputs = derive('input'); + const outputs = derive('output'); + + /** A connection with the new port indices of the node, null if its port is gone */ + const follow = (c: Connection): Connection | null => { + let result = c; + if (c.sourceNodeId === nodeId) { + const i = outputs.index[c.sourcePortIndex]; + if (i == null) return null; + result = { ...result, sourcePortIndex: i }; + } + if (c.targetNodeId === nodeId) { + const i = inputs.index[c.targetPortIndex]; + if (i == null) return null; + result = { ...result, targetPortIndex: i }; + } + return result; + }; + for (const c of level.connections) { + if (follow(c) === null) queueRemoveConnection(c.id); + } + + const update = (n: NodeInstance) => ({ ...n, inputs: inputs.ports, outputs: outputs.ports }); + updateNodesAndConnectionsAt( + path, + (nodes) => { + const n = nodes.get(nodeId); + return n ? new Map(nodes).set(nodeId, update(n)) : nodes; + }, + (nodes) => nodes.map((n) => (n.id === nodeId ? update(n) : n)), + (conns) => conns.map(follow).filter((c): c is Connection => c !== null) + ); +} + // ==================== PUBLIC API ==================== /** diff --git a/src/lib/stores/graph/state.ts b/src/lib/stores/graph/state.ts index 26a8ed5f..205511bf 100644 --- a/src/lib/stores/graph/state.ts +++ b/src/lib/stores/graph/state.ts @@ -295,8 +295,31 @@ export function updateCurrentNodesAndConnections( nodeArrayUpdater: (nodes: NodeInstance[]) => NodeInstance[], connectionUpdater: (connections: Connection[]) => Connection[] ): void { - const path = get(currentPath); + updateNodesAndConnectionsAt(get(currentPath), nodeMapUpdater, nodeArrayUpdater, connectionUpdater); +} + +/** + * Nodes and connections of the level at a subsystem path, the root for an + * empty path, independent of the level shown + */ +export function graphAt(path: string[]): { nodes: NodeInstance[]; connections: Connection[] } { + if (path.length === 0) { + return { nodes: Array.from(get(rootNodes).values()), connections: get(rootConnections) }; + } + const graph = getSubsystemByPath(path)?.graph; + return { nodes: graph?.nodes ?? [], connections: graph?.connections ?? [] }; +} +/** + * Update nodes and connections of the level at a subsystem path, the root for + * an empty path, independent of the level shown + */ +export function updateNodesAndConnectionsAt( + path: string[], + nodeMapUpdater: (nodes: Map) => Map, + nodeArrayUpdater: (nodes: NodeInstance[]) => NodeInstance[], + connectionUpdater: (connections: Connection[]) => Connection[] +): void { if (path.length === 0) { rootNodes.update(nodeMapUpdater); rootConnections.update(connectionUpdater); diff --git a/src/lib/toolbox/installer.ts b/src/lib/toolbox/installer.ts index c578b3c9..efdddf1e 100644 --- a/src/lib/toolbox/installer.ts +++ b/src/lib/toolbox/installer.ts @@ -18,15 +18,21 @@ export interface IntrospectedParam { description: string; } -/** Raw block metadata as returned by pathview_introspect_blocks. */ -export interface IntrospectedBlock { - className: string; - description: string; - docstringHtml: string; +/** Ports of a block as the introspector reports them */ +export interface IntrospectedPorts { inputs: string[] | null; // null = variable ports, else the port labels in channel order outputs: string[] | null; inputBuses?: Record; outputBuses?: Record; +} + +/** Raw block metadata as returned by pathview_introspect_blocks. */ +export interface IntrospectedBlock extends IntrospectedPorts { + className: string; + description: string; + docstringHtml: string; + /** Parameters the ports depend on, the ports above are those of the default parameters */ + portParameters?: string[]; params: IntrospectedParam[]; icon?: string | null; error?: string; @@ -175,6 +181,26 @@ export async function introspectBlocks(importPath: string): Promise { + await ensureHelpers(); + const result = await evaluate<{ ok: boolean; error?: string } & IntrospectedPorts>( + `pathview_block_ports(${pyStr(importPath)}, ${pyStr(className)}, ${pyStr(args)}, ${pyStr(code)})` + ); + if (!result.ok) { + throw new Error(result.error ?? 'unknown error'); + } + return result; +} + /** Import an events submodule and list event classes with their parameters. */ export async function introspectEvents(importPath: string): Promise { await ensureHelpers(); diff --git a/src/lib/toolbox/python.ts b/src/lib/toolbox/python.ts index 1749013a..b2be7c42 100644 --- a/src/lib/toolbox/python.ts +++ b/src/lib/toolbox/python.ts @@ -10,6 +10,8 @@ * - module drop on uninstall * - thin wrappers exposing introspect_blocks / introspect_events / etc. * to the JS evaluate() bridge. + * - the ports of a block built with the parameters of a node, evaluated in + * the model's code context. */ import INTROSPECT_PY from '../../../scripts/pathview_introspect.py?raw'; @@ -92,6 +94,35 @@ def pathview_introspect_events(import_path): return {"ok": True, "events": events} +_pv_context = {"code": None, "namespace": None} + + +def _pv_context_namespace(code): + """Namespace the model's code context ran in, kept until the code changes, + so parameter expressions can use what it defines.""" + if _pv_context["code"] != code: + import numpy as _pv_np + namespace = {"np": _pv_np} + exec(code, namespace) + _pv_context.update(code=code, namespace=namespace) + return _pv_context["namespace"] + + +def pathview_block_ports(import_path, class_name, args, code): + """Ports of a block built with the parameters of a node, 'args' as in the + generated constructor call, evaluated in the model's code context.""" + try: + namespace = _pv_context_namespace(code) + cls = getattr(_pv_importlib.import_module(import_path), class_name) + block = eval(f"_pv_block_class({args})", namespace, {"_pv_block_class": cls}) + ports = instance_ports(block) + except Exception as e: + return {"ok": False, "error": f"{type(e).__name__}: {e}"} + if ports is None: + return {"ok": False, "error": "the installed pathsim does not report the ports of block instances"} + return {"ok": True, **ports} + + def pathview_uninstall(import_path): """Drop a module + submodules from sys.modules.""" return {"ok": True, "dropped": _pv_drop_module(import_path)} diff --git a/src/lib/toolbox/register.ts b/src/lib/toolbox/register.ts index 1c43a9f3..e52c6478 100644 --- a/src/lib/toolbox/register.ts +++ b/src/lib/toolbox/register.ts @@ -68,8 +68,8 @@ function buildBlockDefinition( fallbackCategory: string, importPath: string ) { - const inputs = portsFromLabels(block.inputs); - const outputs = portsFromLabels(block.outputs); + const inputs = portsFromLabels(block.inputs, block.portParameters); + const outputs = portsFromLabels(block.outputs, block.portParameters); const params: Record = {}; for (const p of block.params) { @@ -93,6 +93,7 @@ function buildBlockDefinition( outputBuses: block.outputBuses, inputPolicy: inputs.policy, outputPolicy: outputs.policy, + portParameters: block.portParameters, shape: asShape(selection.override?.shape), syncPorts: selection.override?.syncPorts || undefined, params diff --git a/src/lib/types/nodes.ts b/src/lib/types/nodes.ts index 47e25a74..625d2529 100644 --- a/src/lib/types/nodes.ts +++ b/src/lib/types/nodes.ts @@ -46,10 +46,11 @@ export interface PortInstance { /** * Who sets the ports of a node in one direction: 'fixed' ports come from the - * type definition (or the editor logic of the block), 'variable' ports are - * added and removed by the user + * type definition (or the editor logic of the block), 'derived' ports from the + * pathsim block built with the parameters of the node (see `portParameters`), + * 'variable' ports are added and removed by the user */ -export type PortPolicy = 'fixed' | 'variable'; +export type PortPolicy = 'fixed' | 'derived' | 'variable'; /** Parameter type annotation (mirrors Python type hints) */ export type ParamType = 'number' | 'integer' | 'boolean' | 'string' | 'array' | 'callable' | 'any'; @@ -96,6 +97,9 @@ export interface NodeTypeDefinition { // Parameter definitions params: ParamDefinition[]; + /** Parameters the ports of a pathsim block depend on, see the 'derived' port policy */ + portParameters?: string[]; + // PathSim block class name for export blockClass: string; diff --git a/src/lib/utils/codePreviewHeader.ts b/src/lib/utils/codePreviewHeader.ts index b8d72c83..2449c272 100644 --- a/src/lib/utils/codePreviewHeader.ts +++ b/src/lib/utils/codePreviewHeader.ts @@ -6,8 +6,8 @@ import { nodeRegistry, type NodeInstance } from '$lib/nodes'; import { eventRegistry, type EventInstance } from '$lib/events'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; -import { blockImportPaths } from '$lib/nodes/generated/blocks'; -import { ENGINE_MODULE, enginePath } from '$lib/constants/engine'; +import { ENGINE_MODULE } from '$lib/constants/engine'; +import { blockImportPath } from '$lib/pyodide/codeBuilder'; /** * Extract Python identifiers from a string (parameter values) @@ -136,14 +136,10 @@ export function generateBlockCodeHeader(node: NodeInstance, codeContext: string) const blockClasses = new Set(); collectSubsystemBlockClasses(node, blockClasses); if (blockClasses.size > 0) { - // Group block classes by import path. Toolbox-registered blocks - // carry their own importPath in the typeDef; built-ins fall back - // to the static map. + // Group block classes by import path const importGroups = new Map(); for (const cls of [...blockClasses].sort()) { - const def = nodeRegistry.get(cls); - const importPath = - enginePath(def?.importPath ?? blockImportPaths[cls] ?? 'pathsim.blocks'); + const importPath = blockImportPath(cls); const group = importGroups.get(importPath) || []; group.push(cls); importGroups.set(importPath, group); @@ -153,8 +149,7 @@ export function generateBlockCodeHeader(node: NodeInstance, codeContext: string) } } } else { - const importPath = - enginePath(typeDef.importPath ?? blockImportPaths[typeDef.blockClass] ?? 'pathsim.blocks'); + const importPath = blockImportPath(typeDef.blockClass); lines.push(`from ${importPath} import ${typeDef.blockClass}`); } diff --git a/tests/test_introspect.py b/tests/test_introspect.py index 5a483e91..5efa9acf 100644 --- a/tests/test_introspect.py +++ b/tests/test_introspect.py @@ -1,4 +1,5 @@ -"""Block introspection: ports that are carriers are buses of their channels.""" +"""Block introspection: ports that are carriers are buses of their channels, +ports that depend on parameters come from the block instance.""" import sys from pathlib import Path @@ -7,7 +8,7 @@ from pathsim.utils.carrier import Carrier, Vector sys.path.insert(0, str(Path(__file__).parent.parent / "scripts")) -from pathview_introspect import extract_block # noqa: E402 +from pathview_introspect import extract_block, instance_ports # noqa: E402 class Heater(Block): @@ -40,3 +41,55 @@ class Gain(Block): assert block["outputs"] is None assert block["inputBuses"] == {} assert block["outputBuses"] == {} + + +# ports that depend on parameters ====================================================== + +class _ClassOrInstance: + """info() on the class and on an instance, as pathsim's Block reports it.""" + + def __init__(self, func): + self.func = func + + def __get__(self, obj, cls=None): + return self.func.__get__(cls if obj is None else obj) + + +class Fan: + """One output per weight, like pathsim's Splitter.""" + + input_port_labels = {"in": 0} + output_port_labels = None + port_parameters = ("weights",) + + def __init__(self, weights=(1.0, 1.0)): + self.output_port_labels = {f"out_{i}": i for i in range(len(weights))} + + @_ClassOrInstance + def info(self): + return { + "description": "Fan out.", + "input_port_labels": self.input_port_labels, + "output_port_labels": self.output_port_labels, + "port_parameters": self.port_parameters, + "parameters": {"weights": {"default": (1.0, 1.0)}}, + } + + +def test_ports_from_parameters(): + #the type starts with the ports of the default parameters + block = extract_block(Fan) + assert block["portParameters"] == ["weights"] + assert block["outputs"] == ["out_0", "out_1"] + + #an instance reports its own ports + assert instance_ports(Fan((0.2, 0.3, 0.5)))["outputs"] == ["out_0", "out_1", "out_2"] + + +def test_ports_of_instances_unknown(): + #a pathsim whose info() does not report instances: no instance ports + class Old(Fan): + info = classmethod(lambda cls: {"input_port_labels": cls.input_port_labels, "output_port_labels": None}) + + assert instance_ports(Old()) is None + assert extract_block(Heater)["portParameters"] == []