diff --git a/docs/pvm-spec.md b/docs/pvm-spec.md index 2de480aa..b489692c 100644 --- a/docs/pvm-spec.md +++ b/docs/pvm-spec.md @@ -131,7 +131,8 @@ Ports define the input/output connection points on a node. "name": "in 0", "direction": "input", "index": 0, - "color": "#969696" + "color": "#969696", + "key": "in" } ``` @@ -139,12 +140,14 @@ Ports define the input/output connection points on a node. |-------|------|----------|-------------| | `id` | string | yes | Unique port ID. Convention: `${nodeId}-${direction}-${index}`. | | `nodeId` | string | yes | ID of the owning node. | -| `name` | string | yes | Port display name (e.g., `"in 0"`, `"out 0"`, or a custom label). | +| `name` | string | yes | Port display name (e.g., `"in 0"`, `"out 0"`, or a custom label). Not used by code generation. | | `direction` | string | yes | `"input"` or `"output"`. | | `index` | number | yes | Zero-based port index within the direction. This is the index used by connections. | | `color` | string | no | Port color (hex). Default: `"#969696"`. UI-only. | +| `key` | string | no | Label PathSim addresses the port by, for the fixed ports of a PathSim block. | +| `bus` | array | no | Channels of a port that is a PathSim carrier, as a list of `{"name", "structure"}` signals like a bus (section 4.4). | -**Port semantics for code generation:** The `index` field maps directly to PathSim's port indexing. In generated Python code, `node[0]` refers to the first output port, and connections use the syntax `Connection(source[sourcePortIndex], target[targetPortIndex])`. +**Port semantics for code generation:** A port with a `key` is addressed by it, `node["out"]`, any other port by its `index`, `node[0]`. A single channel of a carrier port is addressed by its name in `bus`, `node["out"]["T"]`, or by its position where the name is the position. Files written before ports carried `key` and `bus` get them from the registry (section 8), by `index`, for block types whose ports are fixed; their `name` is a display name and does not tell the key. ### 3.3 Parameters @@ -486,6 +489,7 @@ The file `scripts/generated/registry.json` maps block type names to their PathSi **For code generators:** Use this registry to: 1. Resolve `node.type` to the correct PathSim class name and import path 2. Filter `node.params` to only include keys listed in `registry.blocks[type].params` (skip `_`-prefixed keys and any keys not in the list) +3. Fill `key` and `bus` of the ports of files written before ports carried them (section 3.2) The full registry is checked into the repo at `scripts/generated/registry.json`. diff --git a/pathview/buses.py b/pathview/buses.py index 29a1953a..158fb304 100644 --- a/pathview/buses.py +++ b/pathview/buses.py @@ -28,13 +28,11 @@ # A signal structure is None for a plain signal, else a list of {"name", "structure"} elements -def port_bus(registry: dict, node: dict, direction: str, index: int): - """Signals of a block port that is a carrier, None for a plain port. The - direction is "inputs" or "outputs", as in the registry.""" - block = registry["blocks"].get(node.get("type", "")) or {} - names = block.get(direction) or [] - buses = block.get("inputBuses" if direction == "inputs" else "outputBuses") or {} - return buses.get(names[index]) if index < len(names) else None +def port_bus(node: dict, direction: str, index: int): + """Signals of a block port that is a carrier, None for a plain port, from + the port of the node. The direction is "inputs" or "outputs".""" + ports = node.get(direction) or [] + return ports[index].get("bus") if index < len(ports) else None def is_bus_block(node: dict) -> bool: @@ -74,16 +72,16 @@ def element_at(structure, path: str): _MISSING = object() -def contains_buses(nodes: list[dict], registry: dict) -> bool: +def contains_buses(nodes: list[dict]) -> bool: """Whether a model has buses: bus blocks or carrier ports, at any level.""" def carrier(node): return any( - port_bus(registry, node, direction, i) + port_bus(node, direction, i) for direction in ("inputs", "outputs") for i in range(len(node.get(direction, []))) ) return any( - is_bus_block(n) or carrier(n) or (bool(n.get("graph")) and contains_buses(n["graph"].get("nodes", []), registry)) + is_bus_block(n) or carrier(n) or (bool(n.get("graph")) and contains_buses(n["graph"].get("nodes", []))) for n in nodes ) @@ -109,8 +107,7 @@ class BusLevel: class BusModel: """Signal structures of a whole model, following wires through bus blocks and subsystems.""" - def __init__(self, nodes: list[dict], connections: list[dict], registry: dict): - self.registry = registry + def __init__(self, nodes: list[dict], connections: list[dict]): self._next_id = 0 self._memo: dict[str, object] = {} self._visiting: set[str] = set() @@ -213,10 +210,10 @@ def _compute_out(self, level: BusLevel, node_id: str, port: int): return None outer, subsystem = level.parent return self.structure_in(outer, subsystem["id"], port) - return port_bus(self.registry, node, "outputs", port) + return port_bus(node, "outputs", port) -def expand_buses(nodes: list[dict], connections: list[dict], registry: dict) -> tuple[list[dict], list[dict]]: +def expand_buses(nodes: list[dict], connections: list[dict]) -> tuple[list[dict], list[dict]]: """The model without bus blocks, for code generation. Models without buses are returned unchanged. Connections that carry @@ -225,9 +222,9 @@ def expand_buses(nodes: list[dict], connections: list[dict], registry: dict) -> Wiring that cannot be resolved, such as a bus into a plain block or a signal missing from a bus, is left out. """ - if not contains_buses(nodes, registry): + if not contains_buses(nodes): return nodes, connections - return _Expansion(BusModel(nodes, connections, registry)).expand() + return _Expansion(BusModel(nodes, connections)).expand() class _Expansion: @@ -246,7 +243,7 @@ def _range(node_id: str, offset: int, length: int) -> list[tuple[str, int, int | def _channels(self, node: dict, direction: str, port: int): """A port of a plain block: all channels of a carrier, else the port itself.""" - carrier = port_bus(self.model.registry, node, direction, port) + carrier = port_bus(node, direction, port) if carrier is None: return [(node["id"], port, None)] return [(node["id"], port, channel) for channel in range(len(carrier))] diff --git a/pathview/converter.py b/pathview/converter.py index 9993b624..eff2e741 100644 --- a/pathview/converter.py +++ b/pathview/converter.py @@ -70,33 +70,55 @@ def generate_param_string(params: dict, valid_params: set[str], multi_line: bool return ", ".join(parts) -def port_key(registry: dict, node_type: str, direction: str, index: int) -> str | int: - """Key of a block port in pathsim: its label for a block type with fixed - ports, whose ports are the labels the pathsim block declares, else its - index. Labeled ports go by label because a label can span several - channels (a carrier), so the position of a port is not its channel index. - Same rule as `portKey` in the editor's code builder.""" - names = (registry["blocks"].get(node_type) or {}).get(direction) - return names[index] if names is not None and index < len(names) else index - - -def port_reference( - var_name: str, registry: dict, node: dict, direction: str, index: int, channel: int | None = None -) -> str: +def with_port_structure(node: dict, registry: dict) -> dict: + """Fill the pathsim key and the carrier channels of the fixed 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 + that have a key, variable ports and unknown types are left as they are. + Same rule as `withPortStructure` in the editor.""" + block = registry["blocks"].get(node.get("type", "")) or {} + node = dict(node) + for direction in ("inputs", "outputs"): + names = block.get(direction) + if names is None: + continue + buses = block.get("inputBuses" if direction == "inputs" else "outputBuses") or {} + ports = [] + for i, port in enumerate(node.get(direction) or []): + if "key" not in port and i < len(names): + port = {**port, "key": names[i], **({"bus": buses[names[i]]} if names[i] in buses else {})} + ports.append(port) + node[direction] = ports + if node.get("graph"): + node["graph"] = {**node["graph"], "nodes": [with_port_structure(n, registry) for n in node["graph"].get("nodes", [])]} + return node + + +def port_key(node: dict, direction: str, index: int) -> str | int: + """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 a label can span several channels (a carrier), so the position of + a port is not its channel index. Same rule as `portKey` in the editor's + code builder.""" + ports = node.get(direction) or [] + key = ports[index].get("key") if index < len(ports) else None + return index if key is None else key + + +def port_reference(var_name: str, node: dict, direction: str, index: int, channel: int | None = None) -> str: """Python reference to a block port, e.g. `amp["in"]` or `scope[0]`, or to a single channel of a carrier port, by its key (`heater["stream"]["T"]`), or by its position where the key is the position, as for a vector.""" - port = f"{var_name}[{json.dumps(port_key(registry, node.get('type', ''), direction, index))}]" + port = f"{var_name}[{json.dumps(port_key(node, direction, index))}]" if channel is None: return port - carrier = port_bus(registry, node, direction, index) or [] + carrier = port_bus(node, direction, index) or [] name = carrier[channel]["name"] if channel < len(carrier) else None return f"{port}[{channel if name is None or name == str(channel) else json.dumps(name)}]" -def group_connections_by_source( - connections: list[dict], nodes: list[dict], node_vars: dict[str, str], registry: dict -) -> list[dict]: +def group_connections_by_source(connections: list[dict], nodes: list[dict], node_vars: dict[str, str]) -> list[dict]: """Group connections by source for multi-target Connection syntax.""" by_id = {n["id"]: n for n in nodes} groups: dict[str, dict] = {} @@ -110,24 +132,24 @@ def group_connections_by_source( if key not in groups: groups[key] = { "source": port_reference( - source_var, registry, by_id.get(conn["sourceNodeId"], {}), "outputs", + source_var, by_id.get(conn["sourceNodeId"], {}), "outputs", conn["sourcePortIndex"], source_channel, ), "targets": [], } groups[key]["targets"].append(port_reference( - target_var, registry, by_id.get(conn["targetNodeId"], {}), "inputs", + target_var, by_id.get(conn["targetNodeId"], {}), "inputs", conn["targetPortIndex"], conn.get("targetChannel"), )) return list(groups.values()) def generate_connection_lines( - connections: list[dict], nodes: list[dict], node_vars: dict[str, str], registry: dict, indent: str = " " + connections: list[dict], nodes: list[dict], node_vars: dict[str, str], indent: str = " " ) -> list[str]: """Generate Connection() lines from the connections between the nodes.""" lines = [] - for group in group_connections_by_source(connections, nodes, node_vars, registry): + for group in group_connections_by_source(connections, nodes, node_vars): lines.append(f"{indent}Connection({group['source']}, {', '.join(group['targets'])}),") return lines @@ -325,7 +347,7 @@ def generate_subsystem_code( lines.append(f" {v},") lines.append(" ],") lines.append(" connections=[") - for line in generate_connection_lines(child_connections, child_nodes, internal_node_vars, registry, " "): + for line in generate_connection_lines(child_connections, child_nodes, internal_node_vars, " "): lines.append(line) lines.append(" ],") if child_events: @@ -348,8 +370,10 @@ def generate_python(pvm: dict, registry: dict, source_name: str = "") -> str: divider = "# " + "\u2500" * 76 graph = pvm.get("graph", {}) + # Ports of files saved before they carried their structure get it from the registry + nodes = [with_port_structure(n, registry) for n in graph.get("nodes", [])] # Bus Creator and Bus Selector exist only in the editor; wire their signals directly - nodes, connections = expand_buses(graph.get("nodes", []), graph.get("connections", []), registry) + nodes, connections = expand_buses(nodes, graph.get("connections", [])) events = pvm.get("events", []) code_context = pvm.get("codeContext", {}).get("code", "") settings = pvm.get("simulationSettings", {}) @@ -475,7 +499,7 @@ def generate_python(pvm: dict, registry: dict, source_name: str = "") -> str: lines.append("connections = []") else: lines.append("connections = [") - for line in generate_connection_lines(connections, nodes, node_vars, registry, " "): + for line in generate_connection_lines(connections, nodes, node_vars, " "): lines.append(line) lines.append("]") lines.append("") diff --git a/src/lib/bus/expand.test.ts b/src/lib/bus/expand.test.ts index 2d6300b4..7e649915 100644 --- a/src/lib/bus/expand.test.ts +++ b/src/lib/bus/expand.test.ts @@ -1,14 +1,16 @@ -import { describe, expect, it } from 'vitest'; +import { afterAll, describe, expect, it } from 'vitest'; import type { BusStructure, Connection, NodeInstance } from '$lib/types/nodes'; import fixtures from '../../../tests/fixtures/bus_expansion.json'; +import { defineNode, portsFromLabels } from '$lib/nodes/defineNode'; +import { nodeRegistry } from '$lib/nodes/registry'; +import { withPortStructure } from '$lib/nodes/ports'; import { analyzeBuses, busWiringProblem, expandBuses, isBusBlock, signalLeaves, - type ExpandedConnection, - type PortBus + type ExpandedConnection } from './expand'; type Scenario = (typeof fixtures.scenarios)[number]; @@ -19,13 +21,26 @@ type Block = { outputBuses?: Record; }; -/** Carrier signals from the block types of the fixture, in the format of registry.json */ -const blocks = fixtures.registry.blocks as Record; -const portBus: PortBus = (node, direction, index) => { - const block = blocks[node.type]; - const name = block?.[direction === 'input' ? 'inputs' : 'outputs'][index]; - return (name !== undefined && block?.[direction === 'input' ? 'inputBuses' : 'outputBuses']?.[name]) || null; -}; +/** The block types of the fixture, in the format of registry.json, registered like extracted blocks */ +const SOURCE = 'expand.test'; +for (const [name, block] of Object.entries(fixtures.registry.blocks as Record)) { + const inputs = portsFromLabels(block.inputs); + const outputs = portsFromLabels(block.outputs); + const definition = defineNode({ + name, + category: 'Test', + blockClass: name, + inputs: inputs.names, + outputs: outputs.names, + labeled: true, + inputBuses: block.inputBuses, + outputBuses: block.outputBuses, + inputPolicy: inputs.policy, + outputPolicy: outputs.policy + }); + nodeRegistry.register(definition, SOURCE); +} +afterAll(() => nodeRegistry.unregisterSource(SOURCE)); const endpoint = (nodeId: string, port: number, channel?: number) => channel === undefined ? `${nodeId}:${port}` : `${nodeId}:${port}[${channel}]`; @@ -51,9 +66,10 @@ function anyBusBlock(nodes: NodeInstance[]): boolean { return nodes.some((n) => isBusBlock(n) || (n.graph ? anyBusBlock(n.graph.nodes) : false)); } +/** A scenario as a saved file is loaded: its ports get their structure from the type definitions */ function load(scenario: Scenario) { return { - nodes: scenario.nodes as unknown as NodeInstance[], + nodes: (scenario.nodes as unknown as NodeInstance[]).map(withPortStructure), connections: scenario.connections as unknown as Connection[] }; } @@ -62,7 +78,7 @@ describe('bus expansion', () => { for (const scenario of fixtures.scenarios) { it(scenario.name, () => { const { nodes, connections } = load(scenario); - const expanded = expandBuses(nodes, connections, portBus); + const expanded = expandBuses(nodes, connections); const expected = Object.fromEntries( Object.entries(scenario.expected as unknown as Record).map(([key, value]) => [ key, @@ -76,14 +92,14 @@ describe('bus expansion', () => { it('returns a model without bus blocks as it is', () => { const { nodes, connections } = load(fixtures.scenarios.find((s) => s.name.includes('without buses'))!); - const expanded = expandBuses(nodes, connections, portBus); + const expanded = expandBuses(nodes, connections); expect(expanded.nodes).toBe(nodes); expect(expanded.connections).toBe(connections); }); it('keeps buses out of plain blocks and plain signals out of selectors', () => { const { nodes, connections } = load(fixtures.scenarios.find((s) => s.name === 'flat creator and selector')!); - const analysis = analyzeBuses(nodes, connections, portBus); + const analysis = analyzeBuses(nodes, connections); const root = analysis.root; expect(busWiringProblem(analysis, root, 'C', 0, 'Scope', 0)).toBe('bus-into-block'); expect(busWiringProblem(analysis, root, 'A', 0, 'S', 0)).toBe('signal-into-selector'); @@ -94,7 +110,7 @@ describe('bus expansion', () => { it('takes a bus into a carrier port only with the signals of the carrier', () => { const creator = load(fixtures.scenarios.find((s) => s.name === 'bus creator into a carrier port')!); - const analysis = analyzeBuses(creator.nodes, creator.connections, portBus); + const analysis = analyzeBuses(creator.nodes, creator.connections); const root = analysis.root; expect(busWiringProblem(analysis, root, 'Cr', 0, 'Tk', 0)).toBeNull(); expect(busWiringProblem(analysis, root, 'A', 0, 'Tk', 0)).toBe('signal-into-carrier'); @@ -102,19 +118,19 @@ describe('bus expansion', () => { // a bus missing a signal of the carrier const partial = creator.connections.filter((c) => c.id !== 'c3'); - const reduced = analyzeBuses(creator.nodes, partial, portBus); + const reduced = analyzeBuses(creator.nodes, partial); expect(busWiringProblem(reduced, reduced.root, 'Cr', 0, 'Tk', 0)).toBe('bus-mismatch'); // a carrier output is a bus const stream = load(fixtures.scenarios.find((s) => s.name === 'carrier into a bus selector')!); - const streams = analyzeBuses(stream.nodes, stream.connections, portBus); + const streams = analyzeBuses(stream.nodes, stream.connections); expect(busWiringProblem(streams, streams.root, 'St', 0, 'S', 0)).toBeNull(); expect(busWiringProblem(streams, streams.root, 'St', 0, 'Scope', 0)).toBe('bus-into-block'); }); it('applies the bus rules across subsystem ports', () => { const { nodes, connections } = load(fixtures.scenarios.find((s) => s.name === 'bus into a subsystem')!); - const analysis = analyzeBuses(nodes, connections, portBus); + const analysis = analyzeBuses(nodes, connections); const inner = analysis.levelAt(['Sub'])!; expect(busWiringProblem(analysis, analysis.root, 'C', 0, 'Sub', 0)).toBeNull(); expect(busWiringProblem(analysis, inner, 'I', 0, 'G', 0)).toBe('bus-into-block'); @@ -123,7 +139,7 @@ describe('bus expansion', () => { it('follows a bus structure into a subsystem', () => { const { nodes, connections } = load(fixtures.scenarios.find((s) => s.name === 'bus into a subsystem')!); - const analysis = analyzeBuses(nodes, connections, portBus); + const analysis = analyzeBuses(nodes, connections); const inner = analysis.levelAt(['Sub'])!; expect(signalLeaves(analysis.structureOut(inner, 'I', 0))).toEqual(['a', 'b']); expect(signalLeaves(analysis.structureIn(analysis.root, 'Scope', 0))).toEqual(['']); diff --git a/src/lib/bus/expand.ts b/src/lib/bus/expand.ts index 4e92fd9b..ca4e9927 100644 --- a/src/lib/bus/expand.ts +++ b/src/lib/bus/expand.ts @@ -18,16 +18,12 @@ import type { BusElement, BusStructure, Connection, NodeInstance, PortDirection } from '$lib/types/nodes'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; -import { nodeRegistry } from '$lib/nodes/registry'; +import { nodePort } from '$lib/nodes/ports'; /** Signals of a block port that is a carrier, null for a plain port */ -export type PortBus = (node: NodeInstance, direction: PortDirection, index: number) => BusStructure; - -/** Carrier signals from the port definitions of the node types */ -export const definitionPortBus: PortBus = (node, direction, index) => { - const ports = nodeRegistry.get(node.type)?.ports; - return (direction === 'input' ? ports?.inputs : ports?.outputs)?.[index]?.bus ?? null; -}; +export function portBus(node: NodeInstance, direction: PortDirection, index: number): BusStructure { + return nodePort(node, direction, index)?.bus ?? null; +} /** A connection after bus expansion; a channel is the position of a single signal within a carrier port */ export interface ExpandedConnection extends Connection { @@ -105,10 +101,10 @@ export function elementAt(structure: BusStructure, path: string): BusElement | u } /** Whether a model has buses: bus blocks or carrier ports, at any level */ -export function containsBuses(nodes: NodeInstance[], portBus: PortBus = definitionPortBus): boolean { +export function containsBuses(nodes: NodeInstance[]): boolean { const carrier = (n: NodeInstance) => n.inputs.some((_, i) => portBus(n, 'input', i)) || n.outputs.some((_, i) => portBus(n, 'output', i)); - return nodes.some((n) => isBusBlock(n) || carrier(n) || (n.graph ? containsBuses(n.graph.nodes, portBus) : false)); + return nodes.some((n) => isBusBlock(n) || carrier(n) || (n.graph ? containsBuses(n.graph.nodes) : false)); } /** Blocks that wiring passes through unchanged: neither bus blocks nor subsystem boundaries */ @@ -120,7 +116,7 @@ function isPlainBlock(node: NodeInstance): boolean { * Signal structures of a whole model. Structures follow wires through Bus * Creators, Bus Selectors and subsystem boundaries in both directions. */ -export function analyzeBuses(nodes: NodeInstance[], connections: Connection[], portBus: PortBus = definitionPortBus) { +export function analyzeBuses(nodes: NodeInstance[], connections: Connection[]) { let nextLevelId = 0; function buildLevel(nodeList: NodeInstance[], levelConnections: Connection[], parent: BusLevel['parent']): BusLevel { @@ -224,7 +220,7 @@ export function analyzeBuses(nodes: NodeInstance[], connections: Connection[], p return level; } - return { root, levelAt, structureIn, structureOut, elementNames, portBus }; + return { root, levelAt, structureIn, structureOut, elementNames }; } export type BusAnalysis = ReturnType; @@ -257,7 +253,7 @@ export function busWiringProblem( case NODE_TYPES.BUS_SELECTOR: return structure ? null : 'signal-into-selector'; default: { - const carrier = analysis.portBus(target, 'input', targetPort); + const carrier = portBus(target, 'input', targetPort); if (!carrier) return structure ? 'bus-into-block' : null; if (!structure) return 'signal-into-carrier'; return signalLeaves(structure).join() === signalLeaves(carrier).join() ? null : 'bus-mismatch'; @@ -274,12 +270,11 @@ export function busWiringProblem( */ export function expandBuses( nodes: NodeInstance[], - connections: Connection[], - portBus: PortBus = definitionPortBus + connections: Connection[] ): { nodes: NodeInstance[]; connections: ExpandedConnection[] } { - if (!containsBuses(nodes, portBus)) return { nodes, connections }; + if (!containsBuses(nodes)) return { nodes, connections }; - const { root, structureIn, structureOut } = analyzeBuses(nodes, connections, portBus); + const { root, structureIn, structureOut } = analyzeBuses(nodes, connections); const count = (structure: BusStructure) => signalLeaves(structure).length; const range = (nodeId: string, offset: number, length: number): Endpoint[] => Array.from({ length }, (_, j) => ({ nodeId, port: offset + j })); diff --git a/src/lib/components/FlowCanvas.svelte b/src/lib/components/FlowCanvas.svelte index 3f9d06a6..f2be3d3f 100644 --- a/src/lib/components/FlowCanvas.svelte +++ b/src/lib/components/FlowCanvas.svelte @@ -845,7 +845,7 @@ if (!targetNode) return; const typeDef = nodeRegistry.get(targetNode.type); - if (!typeDef || typeDef.ports.maxInputs !== null) { + if (!typeDef || typeDef.ports.inputPolicy !== 'variable') { // Can't create new port, abort return; } diff --git a/src/lib/components/nodes/BaseNode.svelte b/src/lib/components/nodes/BaseNode.svelte index 9bdda4f4..87bfa22b 100644 --- a/src/lib/components/nodes/BaseNode.svelte +++ b/src/lib/components/nodes/BaseNode.svelte @@ -184,8 +184,8 @@ }); // Check if this node allows dynamic ports - const allowsDynamicInputs = $derived(typeDef?.ports.maxInputs === null); - const allowsDynamicOutputs = $derived(typeDef?.ports.maxOutputs === null); + const allowsDynamicInputs = $derived(typeDef?.ports.inputPolicy === 'variable'); + const allowsDynamicOutputs = $derived(typeDef?.ports.outputPolicy === 'variable'); const syncPorts = $derived(typeDef?.ports.syncPorts ?? false); // Rotation state (0, 1, 2, 3 = 0°, 90°, 180°, 270°) - stored in node params diff --git a/src/lib/nodes/buses.ts b/src/lib/nodes/buses.ts index d11f48f1..1dc4405d 100644 --- a/src/lib/nodes/buses.ts +++ b/src/lib/nodes/buses.ts @@ -28,9 +28,9 @@ export const BusCreatorDefinition = defineNode({ inputs: ['in 0', 'in 1'], outputs: ['bus'], minInputs: 1, - maxInputs: null, + inputPolicy: 'variable', minOutputs: 1, - maxOutputs: 1, + outputPolicy: 'fixed', shape: 'rect', params: {} }); @@ -44,9 +44,9 @@ export const BusSelectorDefinition = defineNode({ inputs: ['bus'], outputs: [], minInputs: 1, - maxInputs: 1, + inputPolicy: 'fixed', minOutputs: 0, - maxOutputs: 0, + outputPolicy: 'fixed', // set by the picked signals shape: 'rect', params: { signals: { type: 'any', default: [], description: 'Signal paths picked from the bus, one output each' } diff --git a/src/lib/nodes/defineNode.test.ts b/src/lib/nodes/defineNode.test.ts index 95ca3421..cbb25d6f 100644 --- a/src/lib/nodes/defineNode.test.ts +++ b/src/lib/nodes/defineNode.test.ts @@ -19,6 +19,24 @@ describe('defineNode', () => { expect(def.ports.outputs[0].bus).toEqual(signals('F', 'T', 'P')); }); + it('gives the fixed ports of a pathsim block their label as key', () => { + const def = defineNode({ + name: 'Atan2', + category: 'Algebraic', + blockClass: 'Atan2', + inputs: ['a', 'b'], + outputs: ['y'], + labeled: true, + inputPolicy: 'fixed', + outputPolicy: 'fixed' + }); + expect(def.ports.inputs.map((p) => p.key)).toEqual(['a', 'b']); + + //variable ports and ports the editor names have none + expect(defineNode({ name: 'Gain', category: 'Algebraic', blockClass: 'Amplifier', labeled: true }).ports.inputs[0]).not.toHaveProperty('key'); + expect(defineNode({ name: 'Bus', category: 'Buses', blockClass: 'BusCreator', outputs: ['bus'], outputPolicy: 'fixed' }).ports.outputs[0]).not.toHaveProperty('key'); + }); + it('leaves plain ports without a bus', () => { const def = defineNode({ name: 'Gain', category: 'Algebraic', blockClass: 'Amplifier' }); expect(def.ports.inputs[0]).not.toHaveProperty('bus'); diff --git a/src/lib/nodes/defineNode.ts b/src/lib/nodes/defineNode.ts index d9ee42e7..ddb0a922 100644 --- a/src/lib/nodes/defineNode.ts +++ b/src/lib/nodes/defineNode.ts @@ -3,7 +3,7 @@ * Factory function for creating node type definitions */ -import type { NodeTypeDefinition, NodeCategory, ParamType, ParamDefinition, NodeShape, BusStructure } from './types'; +import type { NodeTypeDefinition, NodeCategory, ParamType, ParamDefinition, NodeShape, BusStructure, PortPolicy } from './types'; import { PORT_COLORS } from '$lib/utils/colors'; interface DefineNodeOptions { @@ -19,13 +19,15 @@ interface DefineNodeOptions { // Port configuration inputs?: string[]; // Named input ports outputs?: string[]; // Named output ports + /** The names of the fixed ports are the labels pathsim addresses them by */ + labeled?: boolean; /** Signals of the ports that are carriers, by port name */ inputBuses?: Record; outputBuses?: Record; minInputs?: number; // minimum ports (default 1) minOutputs?: number; - maxInputs?: number | null; // null = unlimited - maxOutputs?: number | null; + inputPolicy?: PortPolicy; // default 'variable' + outputPolicy?: PortPolicy; syncPorts?: boolean; // When true, output count always equals input count // Shape override (defaults based on category) @@ -45,6 +47,14 @@ 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 + */ +export function portsFromLabels(labels: string[] | null | undefined): { names: string[] | undefined; policy: PortPolicy } { + return labels == null ? { names: undefined, policy: 'variable' } : { names: labels, policy: 'fixed' }; +} + /** * Create a node type definition */ @@ -57,12 +67,13 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition { importPath, inputs = ['in 0'], outputs = ['out 0'], + labeled = false, inputBuses = {}, outputBuses = {}, minInputs = 1, minOutputs = 1, - maxInputs = null, - maxOutputs = null, + inputPolicy = 'variable', + outputPolicy = 'variable', syncPorts, shape, params = {} @@ -93,18 +104,20 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition { name: portName, direction: 'input' as const, color: PORT_COLORS.default, + ...(labeled && inputPolicy === 'fixed' ? { 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 } : {}), ...(outputBuses[portName] ? { bus: outputBuses[portName] } : {}) })), minInputs, minOutputs, - maxInputs, - maxOutputs, + inputPolicy, + outputPolicy, syncPorts }, diff --git a/src/lib/nodes/ports.test.ts b/src/lib/nodes/ports.test.ts new file mode 100644 index 00000000..bfa959db --- /dev/null +++ b/src/lib/nodes/ports.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import type { NodeInstance, PortInstance } from './types'; +import { withPortStructure } from './ports'; + +/** Ports as saved before they carried their structure: display names only */ +const ports = (nodeId: string, direction: 'input' | 'output', names: string[]) => + names.map((name, index) => ({ id: `${nodeId}-${direction}-${index}`, nodeId, name, direction, index, color: '' }) as PortInstance); +const node = (id: string, type: string, inputs: string[], outputs: string[]) => + ({ id, type, name: id, params: {}, position: { x: 0, y: 0 }, inputs: ports(id, 'input', inputs), outputs: ports(id, 'output', outputs) }) as NodeInstance; + +describe('port structure of loaded nodes', () => { + it('takes the keys of fixed ports from the type definition by index, not from the display names', () => { + const atan = withPortStructure(node('a', 'Atan2', ['in 0', 'in 1'], ['out 0'])); + expect(atan.inputs.map((p) => p.key)).toEqual(['a', 'b']); + expect(atan.outputs[0]).toMatchObject({ name: 'out 0', key: 'y' }); + }); + + it('keeps keys the ports carry and leaves variable ports and unknown types as they are', () => { + const constant = node('c', 'Constant', [], ['out']); + constant.outputs[0].key = 'kept'; + expect(withPortStructure(constant).outputs[0].key).toBe('kept'); + + const scope = node('s', 'Scope', ['in 0'], []); + expect(withPortStructure(scope)).toBe(scope); + const unknown = node('u', 'Unknown', ['in 0'], []); + expect(withPortStructure(unknown)).toBe(unknown); + }); + + it('fills nodes inside subsystems', () => { + const sub = { ...node('sub', 'Subsystem', [], []), graph: { nodes: [node('c', 'Constant', [], ['out 0'])], connections: [] } }; + expect(withPortStructure(sub).graph?.nodes[0].outputs[0].key).toBe('out'); + }); +}); diff --git a/src/lib/nodes/ports.ts b/src/lib/nodes/ports.ts new file mode 100644 index 00000000..575a7e89 --- /dev/null +++ b/src/lib/nodes/ports.ts @@ -0,0 +1,56 @@ +/** + * Port structure of nodes + * + * Each port of a node carries how pathsim addresses it (`key`, the label of a + * fixed port of a pathsim block) and the channels of a carrier port (`bus`). + * Code generation and the bus analysis read them from the node only. + */ + +import type { NodeInstance, PortDirection, PortInstance } from './types'; +import { nodeRegistry } from './registry'; + +/** Port of a node by direction and index */ +export function nodePort(node: NodeInstance, direction: PortDirection, index: number): PortInstance | undefined { + return (direction === 'input' ? node.inputs : node.outputs)?.[index]; +} + +/** + * 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. + */ +export function withPortStructure(node: NodeInstance): NodeInstance { + let result = node; + const typeDef = nodeRegistry.get(node.type); + if (typeDef) { + 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; + 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; + result = { + ...result, + [portsKey]: ports.map((port, i) => + port.key !== undefined + ? port + : { + ...port, + ...(defs[i]?.key !== undefined ? { key: defs[i].key } : {}), + ...(defs[i]?.bus ? { bus: defs[i].bus } : {}) + } + ) + }; + } + } + if (result.graph) { + const nodes = result.graph.nodes.map(withPortStructure); + if (nodes.some((n, i) => n !== result.graph!.nodes[i])) { + result = { ...result, graph: { ...result.graph, nodes } }; + } + } + return result; +} diff --git a/src/lib/nodes/registry.ts b/src/lib/nodes/registry.ts index f45f2e35..d3bced0c 100644 --- a/src/lib/nodes/registry.ts +++ b/src/lib/nodes/registry.ts @@ -14,7 +14,7 @@ import { writable, type Readable } from 'svelte/store'; import type { NodeTypeDefinition, NodeCategory, ParamDefinition, ParamType } from './types'; -import { defineNode } from './defineNode'; +import { defineNode, portsFromLabels } from './defineNode'; import { extractedBlocks, blockConfig, type ExtractedBlock } from './generated/blocks'; import { syncPortBlocks } from './uiConfig'; @@ -177,53 +177,21 @@ function createNodeFromExtracted( }; } - // Determine inputs from extracted data - let inputs: string[] | undefined; - let maxInputs: number | null; - - if (extracted.inputs === null) { - // Variable ports - use default, UI will allow add/remove - inputs = undefined; // defineNode will use ['in 0'] - maxInputs = null; // unlimited - } else if (extracted.inputs.length > 0) { - // Fixed labeled ports - inputs = extracted.inputs; - maxInputs = extracted.inputs.length; - } else { - // Empty array means no inputs - inputs = []; - maxInputs = 0; - } - - // Determine outputs from extracted data - let outputs: string[] | undefined; - let maxOutputs: number | null; - - if (extracted.outputs === null) { - // Variable ports - use default, UI will allow add/remove - outputs = undefined; // defineNode will use ['out 0'] - maxOutputs = null; // unlimited - } else if (extracted.outputs.length > 0) { - // Fixed labeled ports - outputs = extracted.outputs; - maxOutputs = extracted.outputs.length; - } else { - // Empty array means no outputs - outputs = []; - maxOutputs = 0; - } + const inputs = portsFromLabels(extracted.inputs); + const outputs = portsFromLabels(extracted.outputs); const definition = defineNode({ name, category, blockClass: extracted.blockClass, description: extracted.description, - inputs, - outputs, + inputs: inputs.names, + outputs: outputs.names, + labeled: true, inputBuses: extracted.inputBuses, outputBuses: extracted.outputBuses, - maxInputs, - maxOutputs, + inputPolicy: inputs.policy, + outputPolicy: outputs.policy, syncPorts: syncPortBlocks.has(name), params }); diff --git a/src/lib/nodes/subsystem.ts b/src/lib/nodes/subsystem.ts index 3349fcdf..42b52396 100644 --- a/src/lib/nodes/subsystem.ts +++ b/src/lib/nodes/subsystem.ts @@ -21,8 +21,8 @@ export const SubsystemDefinition = defineNode({ outputs: [], minInputs: 0, // Ports controlled by Interface minOutputs: 0, - maxInputs: null, // Dynamic based on Interface - maxOutputs: null, + inputPolicy: 'variable', // Dynamic based on Interface + outputPolicy: 'variable', shape: 'rect', params: {} }); @@ -44,8 +44,8 @@ export const InterfaceDefinition = defineNode({ outputs: [], minInputs: 0, // Interface can have zero ports minOutputs: 0, - maxInputs: null, - maxOutputs: null, + inputPolicy: 'variable', + outputPolicy: 'variable', shape: 'rect', params: {} }); diff --git a/src/lib/nodes/types.ts b/src/lib/nodes/types.ts index 9ac4b48a..779c375f 100644 --- a/src/lib/nodes/types.ts +++ b/src/lib/nodes/types.ts @@ -11,6 +11,7 @@ export type { BusElement, PortDefinition, PortInstance, + PortPolicy, ParamType, ParamDefinition, NodeCategory, diff --git a/src/lib/pyodide/codeBuilder.test.ts b/src/lib/pyodide/codeBuilder.test.ts index d13294df..a84cc1f2 100644 --- a/src/lib/pyodide/codeBuilder.test.ts +++ b/src/lib/pyodide/codeBuilder.test.ts @@ -2,10 +2,20 @@ import { afterAll, describe, it, expect } from 'vitest'; import type { NodeInstance } from '$lib/nodes/types'; import { defineNode } from '$lib/nodes/defineNode'; import { nodeRegistry } from '$lib/nodes/registry'; +import { createPorts } from '$lib/stores/graph/helpers'; import type { ExpandedConnection } from '$lib/bus/expand'; import { generateNamedConnections, portKey } from './codeBuilder'; -const node = (id: string, type: string) => ({ id, type }) as NodeInstance; +/** A node with the ports of its type, as a node added in the editor */ +const node = (id: string, type: string) => { + const ports = nodeRegistry.get(type)?.ports; + return { + id, + type, + inputs: createPorts(id, 'input', ports?.inputs ?? []), + outputs: createPorts(id, 'output', ports?.outputs ?? []) + } as NodeInstance; +}; const wire = (source: string, sourcePort: number, target: string, targetPort: number): ExpandedConnection => ({ id: `${source}-${target}-${targetPort}`, sourceNodeId: source, @@ -17,10 +27,16 @@ const signals = (...names: string[]) => names.map((name) => ({ name, structure: describe('port keys', () => { it('addresses labeled ports by label and variable ports by index', () => { - expect(portKey('Atan2', 'input', 1)).toBe('b'); - expect(portKey('Atan2', 'output', 0)).toBe('y'); - expect(portKey('Scope', 'input', 2)).toBe(2); - expect(portKey('Unknown', 'input', 0)).toBe(0); + expect(portKey(node('a', 'Atan2'), 'input', 1)).toBe('b'); + expect(portKey(node('a', 'Atan2'), 'output', 0)).toBe('y'); + expect(portKey(node('s', 'Scope'), 'input', 2)).toBe(2); + expect(portKey(node('u', 'Unknown'), 'input', 0)).toBe(0); + }); + + it('keeps the label when the user renames the port', () => { + const atan = node('a', 'Atan2'); + atan.inputs[1] = { ...atan.inputs[1], name: 'denominator' }; + expect(portKey(atan, 'input', 1)).toBe('b'); }); it('generates connections with the port keys', () => { @@ -47,8 +63,9 @@ describe('carrier channels', () => { blockClass: name, inputs: [], outputs: ['out'], - maxInputs: 0, - maxOutputs: 1, + labeled: true, + inputPolicy: 'fixed', + outputPolicy: 'fixed', outputBuses: { out: [...bus] } }); nodeRegistry.register(definition, SOURCE); diff --git a/src/lib/pyodide/codeBuilder.ts b/src/lib/pyodide/codeBuilder.ts index a531735e..00cb70b5 100644 --- a/src/lib/pyodide/codeBuilder.ts +++ b/src/lib/pyodide/codeBuilder.ts @@ -4,8 +4,8 @@ */ import type { NodeInstance, PortDirection } from '$lib/nodes/types'; -import { nodeRegistry } from '$lib/nodes/registry'; -import { definitionPortBus, type ExpandedConnection } from '$lib/bus/expand'; +import { nodePort } from '$lib/nodes/ports'; +import type { ExpandedConnection } from '$lib/bus/expand'; /** Options for parameter string generation */ export interface ParamStringOptions { @@ -54,17 +54,13 @@ export function generateParamString( } /** - * Key of a block port in pathsim: its label for a block type with fixed ports, - * whose ports are the labels the pathsim block declares, else its index. - * Labeled ports go by label because a label can span several channels (a - * carrier), so the position of a port is not its channel index. + * 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 + * a label can span several channels (a carrier), so the position of a port is + * not its channel index. */ -export function portKey(type: string, direction: PortDirection, index: number): string | number { - const ports = nodeRegistry.get(type)?.ports; - if (!ports) return index; - const fixed = (direction === 'input' ? ports.maxInputs : ports.maxOutputs) !== null; - const name = (direction === 'input' ? ports.inputs : ports.outputs)[index]?.name; - return fixed && name !== undefined ? name : index; +export function portKey(node: NodeInstance, direction: PortDirection, index: number): string | number { + return nodePort(node, direction, index)?.key ?? index; } /** @@ -73,9 +69,9 @@ export function portKey(type: string, direction: PortDirection, index: number): * by its position where the key is the position, as for a vector */ function portReference(node: NodeInstance, varName: string, direction: PortDirection, index: number, channel?: number): string { - const port = `${varName}[${JSON.stringify(portKey(node.type, direction, index))}]`; + const port = `${varName}[${JSON.stringify(portKey(node, direction, index))}]`; if (channel === undefined) return port; - const name = definitionPortBus(node, direction, index)?.[channel]?.name; + const name = nodePort(node, direction, index)?.bus?.[channel]?.name; return `${port}[${name === undefined || name === String(channel) ? channel : JSON.stringify(name)}]`; } diff --git a/src/lib/pyodide/mutationQueue.ts b/src/lib/pyodide/mutationQueue.ts index 047ea9ec..0e250f1e 100644 --- a/src/lib/pyodide/mutationQueue.ts +++ b/src/lib/pyodide/mutationQueue.ts @@ -218,9 +218,9 @@ export function queueAddConnection(conn: Connection, source: NodeInstance, targe type: 'add_connection', var: varName, sourceVar, - sourcePort: portKey(source.type, 'output', conn.sourcePortIndex), + sourcePort: portKey(source, 'output', conn.sourcePortIndex), targetVar, - targetPort: portKey(target.type, 'input', conn.targetPortIndex) + targetPort: portKey(target, 'input', conn.targetPortIndex) }); updateCount(); } diff --git a/src/lib/schema/fileOps.ts b/src/lib/schema/fileOps.ts index f484be91..a83f2393 100644 --- a/src/lib/schema/fileOps.ts +++ b/src/lib/schema/fileOps.ts @@ -9,6 +9,7 @@ import { tick } from 'svelte'; import { writable, get } from 'svelte/store'; import type { NodeInstance, Connection, SimulationSettings, GraphFile, SolverType } from '$lib/nodes/types'; import { GRAPH_FILE_VERSION, INITIAL_SIMULATION_SETTINGS } from '$lib/nodes/types'; +import { withPortStructure } from '$lib/nodes/ports'; import type { ComponentFile, ComponentType, BlockContent, SubsystemContent } from '$lib/types/component'; import type { Position } from '$lib/types'; import { ALL_COMPONENT_EXTENSIONS, COMPONENT_VERSION } from '$lib/types/component'; @@ -684,7 +685,7 @@ async function importComponent( } // Clone node with new IDs (handles subsystem graph regeneration automatically) - const newNode = cloneNodeForPaste(node, position); + const newNode = withPortStructure(cloneNodeForPaste(node, position)); // Clear selection and add node historyStore.mutate(() => { diff --git a/src/lib/stores/clipboard.ts b/src/lib/stores/clipboard.ts index f5243666..b5f10956 100644 --- a/src/lib/stores/clipboard.ts +++ b/src/lib/stores/clipboard.ts @@ -5,6 +5,7 @@ import { writable, get } from 'svelte/store'; import type { NodeInstance, Connection, Annotation } from '$lib/nodes/types'; +import { withPortStructure } from '$lib/nodes/ports'; import type { EventInstance } from '$lib/events/types'; import type { Position } from '$lib/types'; import { graphStore, cloneNodeForPaste } from '$lib/stores/graph'; @@ -324,7 +325,7 @@ async function paste(targetPosition: Position): Promise<{ nodeIds: string[]; eve }); // Use shared utility for node cloning (handles subsystem ID regeneration) - const newNode = cloneNodeForPaste(node, newPosition, newId); + const newNode = withPortStructure(cloneNodeForPaste(node, newPosition, newId)); nodesToPaste.push(newNode); } diff --git a/src/lib/stores/graph/helpers.ts b/src/lib/stores/graph/helpers.ts index eeaa2250..34b29001 100644 --- a/src/lib/stores/graph/helpers.ts +++ b/src/lib/stores/graph/helpers.ts @@ -3,7 +3,7 @@ * Pure functions that don't depend on store state */ -import type { PortInstance, NodeInstance, SubsystemGraph, Connection } from '$lib/nodes/types'; +import type { PortInstance, PortDefinition, NodeInstance, SubsystemGraph, Connection } from '$lib/nodes/types'; import { PORT_COLORS } from '$lib/utils/colors'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; @@ -12,12 +12,13 @@ import { generateId } from '$lib/stores/utils'; export { generateId }; /** - * Create port instances from port definitions + * Create port instances from port definitions, with the pathsim key and the + * carrier channels of the definitions */ export function createPorts( nodeId: string, direction: 'input' | 'output', - portDefs: { name: string; color?: string }[] + portDefs: Pick[] ): PortInstance[] { return portDefs.map((def, index) => ({ id: `${nodeId}-${direction}-${index}`, @@ -25,7 +26,9 @@ export function createPorts( name: def.name, direction, index, - color: def.color || PORT_COLORS.default + color: def.color || PORT_COLORS.default, + ...(def.key !== undefined ? { key: def.key } : {}), + ...(def.bus ? { bus: def.bus } : {}) })); } @@ -53,38 +56,6 @@ export function getSubsystemByPath( return subsystem; } -/** - * Derive Interface node ports from parent Subsystem - * Interface outputs = Subsystem inputs (signals coming in) - * Interface inputs = Subsystem outputs (signals going out) - */ -export function deriveInterfaceNode( - interfaceNode: NodeInstance, - parentSubsystem: NodeInstance -): NodeInstance { - return { - ...interfaceNode, - name: parentSubsystem.name, - color: parentSubsystem.color, - outputs: parentSubsystem.inputs.map((port, i) => ({ - id: `${interfaceNode.id}-output-${i}`, - nodeId: interfaceNode.id, - name: port.name, - direction: 'output' as const, - index: i, - color: port.color - })), - inputs: parentSubsystem.outputs.map((port, i) => ({ - id: `${interfaceNode.id}-input-${i}`, - nodeId: interfaceNode.id, - name: port.name, - direction: 'input' as const, - index: i, - color: port.color - })) - }; -} - /** * Collect all nodes recursively from a subsystem hierarchy */ @@ -167,73 +138,6 @@ export function findParentSubsystem(nodes: NodeInstance[], interfaceId: string): return null; } -/** - * Clone a node for duplication - * Creates a deep copy to avoid shared references - */ -export function cloneNode( - node: NodeInstance, - newId: string, - positionOffset: { x: number; y: number } -): NodeInstance { - return { - id: newId, - type: node.type, - name: node.name, - position: { - x: node.position.x + positionOffset.x, - y: node.position.y + positionOffset.y - }, - inputs: createPorts( - newId, - 'input', - node.inputs.map((p) => ({ name: p.name, color: p.color })) - ), - outputs: createPorts( - newId, - 'output', - node.outputs.map((p) => ({ name: p.name, color: p.color })) - ), - // Deep clone params to avoid shared references - params: structuredClone(node.params), - // Copy pinnedParams array if present - pinnedParams: node.pinnedParams ? [...node.pinnedParams] : undefined, - color: node.color, - // Deep clone graph for subsystems - graph: node.graph ? structuredClone(node.graph) : undefined - }; -} - -/** - * Update ports array with new port count - */ -export function resizePorts( - nodeId: string, - currentPorts: PortInstance[], - newCount: number, - direction: 'input' | 'output' -): PortInstance[] { - if (newCount < currentPorts.length) { - // Remove ports from the end - return currentPorts.slice(0, newCount); - } else if (newCount > currentPorts.length) { - // Add new ports - const newPorts = [...currentPorts]; - for (let i = currentPorts.length; i < newCount; i++) { - newPorts.push({ - id: `${nodeId}-${direction}-${i}`, - nodeId, - name: direction === 'input' ? `in ${i}` : `out ${i}`, - direction, - index: i, - color: PORT_COLORS.default - }); - } - return newPorts; - } - return currentPorts; -} - /** * Clone a node for paste/import operations * Creates a new node with regenerated IDs at the given position diff --git a/src/lib/stores/graph/index.ts b/src/lib/stores/graph/index.ts index 9f4a5fbf..efb26321 100644 --- a/src/lib/stores/graph/index.ts +++ b/src/lib/stores/graph/index.ts @@ -129,11 +129,9 @@ export { generateId, createPorts, getSubsystemByPath, - deriveInterfaceNode, isSubsystemNode, isInterfaceNode, findParentSubsystem, - cloneNode, cloneNodeForPaste, regenerateGraphIds } from './helpers'; diff --git a/src/lib/stores/graph/ports.ts b/src/lib/stores/graph/ports.ts index 82309784..193053ec 100644 --- a/src/lib/stores/graph/ports.ts +++ b/src/lib/stores/graph/ports.ts @@ -29,7 +29,7 @@ function getPortConfig(direction: PortDirection) { portsKey: direction === 'input' ? 'inputs' : 'outputs', oppositeKey: direction === 'input' ? 'outputs' : 'inputs', minKey: direction === 'input' ? 'minInputs' : 'minOutputs', - maxKey: direction === 'input' ? 'maxInputs' : 'maxOutputs', + policyKey: direction === 'input' ? 'inputPolicy' : 'outputPolicy', connectionKey: direction === 'input' ? 'targetNodeId' : 'sourceNodeId', connectionIndexKey: direction === 'input' ? 'targetPortIndex' : 'sourcePortIndex', defaultName: direction === 'input' ? 'in' : 'out' @@ -108,11 +108,10 @@ function addPort(nodeId: string, direction: PortDirection, syncFollowUp = false) return true; } - // Normal node: check max ports limit + // Normal node: only variable ports are added by the user const typeDef = nodeRegistry.get(node.type); - const maxPorts = typeDef?.ports[config.maxKey]; + if (typeDef && typeDef.ports[config.policyKey] !== 'variable') return false; const currentPorts = node[config.portsKey] as PortInstance[]; - if (maxPorts != null && currentPorts.length >= maxPorts) return false; // Create new port const index = currentPorts.length; diff --git a/src/lib/stores/graph/serialization.ts b/src/lib/stores/graph/serialization.ts index 49f00eda..e62e9b79 100644 --- a/src/lib/stores/graph/serialization.ts +++ b/src/lib/stores/graph/serialization.ts @@ -6,6 +6,8 @@ import { get } from 'svelte/store'; import type { NodeInstance, Connection, Annotation } from '$lib/nodes/types'; import { NODE_TYPES } from '$lib/constants/nodeTypes'; import { applyPortLabelSync } from './ports'; +import { withPortStructure } from '$lib/nodes/ports'; +import { registryVersion } from '$lib/nodes/registry'; import { rootNodes, rootConnections, @@ -57,6 +59,24 @@ function syncPortLabelsRecursively(nodes: NodeInstance[]): NodeInstance[] { }); } +/** + * Fill the port structure of nodes whose type registers after they were + * loaded, such as the blocks of a toolbox that installs after the file is + * shown (see `loadGraphFile`) + */ +registryVersion.subscribe(() => { + rootNodes.update((nodes) => { + let changed = false; + const filled = new Map(); + for (const [id, node] of nodes) { + const next = withPortStructure(node); + changed ||= next !== node; + filled.set(id, next); + } + return changed ? filled : nodes; + }); +}); + /** * Load state from JSON */ @@ -64,7 +84,7 @@ export function fromJSON(nodeList: NodeInstance[], connectionList: Connection[], if (!nodeList || !Array.isArray(nodeList)) { rootNodes.set(new Map()); } else { - const synced = syncPortLabelsRecursively(nodeList); + const synced = syncPortLabelsRecursively(nodeList.map(withPortStructure)); rootNodes.set(new Map(synced.map(n => [n.id, n]))); } rootConnections.set(connectionList || []); diff --git a/src/lib/toolbox/installer.ts b/src/lib/toolbox/installer.ts index 1874ad64..c578b3c9 100644 --- a/src/lib/toolbox/installer.ts +++ b/src/lib/toolbox/installer.ts @@ -23,8 +23,8 @@ export interface IntrospectedBlock { className: string; description: string; docstringHtml: string; - inputs: Record | string[] | null; - outputs: Record | string[] | null; + inputs: string[] | null; // null = variable ports, else the port labels in channel order + outputs: string[] | null; inputBuses?: Record; outputBuses?: Record; params: IntrospectedParam[]; diff --git a/src/lib/toolbox/register.ts b/src/lib/toolbox/register.ts index ff06d889..1c43a9f3 100644 --- a/src/lib/toolbox/register.ts +++ b/src/lib/toolbox/register.ts @@ -6,7 +6,7 @@ * `unregisterSource(id)` is the clean uninstall path. */ -import { defineNode } from '$lib/nodes/defineNode'; +import { defineNode, portsFromLabels } from '$lib/nodes/defineNode'; import { nodeRegistry } from '$lib/nodes/registry'; import type { NodeShape, ParamType } from '$lib/nodes/types'; import { eventRegistry } from '$lib/events/registry'; @@ -28,28 +28,6 @@ import { import { upsertToolbox } from './store'; import type { BlockSelection, EventSelection, ToolboxConfig } from './types'; -/** - * Resolve the port shape from introspected `input_port_labels` / `output_port_labels`. - * Same semantics as the build-time pipeline. - */ -function resolvePorts( - labels: Record | string[] | null | undefined -): { ports: string[] | undefined; max: number | null } { - if (labels === null || labels === undefined) { - return { ports: undefined, max: null }; // variable - } - if (Array.isArray(labels)) { - if (labels.length === 0) return { ports: [], max: 0 }; - return { ports: labels, max: labels.length }; - } - // Dict {name: index} - const entries = Object.entries(labels); - if (entries.length === 0) return { ports: [], max: 0 }; - entries.sort((a, b) => (a[1] as number) - (b[1] as number)); - const ports = entries.map(([name]) => name); - return { ports, max: ports.length }; -} - const PARAM_TYPES: ReadonlySet = new Set([ 'number', 'integer', @@ -90,8 +68,8 @@ function buildBlockDefinition( fallbackCategory: string, importPath: string ) { - const { ports: inputs, max: maxInputs } = resolvePorts(block.inputs); - const { ports: outputs, max: maxOutputs } = resolvePorts(block.outputs); + const inputs = portsFromLabels(block.inputs); + const outputs = portsFromLabels(block.outputs); const params: Record = {}; for (const p of block.params) { @@ -108,12 +86,13 @@ function buildBlockDefinition( blockClass: block.className, importPath, description: block.description, - inputs, - outputs, + inputs: inputs.names, + outputs: outputs.names, + labeled: true, inputBuses: block.inputBuses, outputBuses: block.outputBuses, - maxInputs, - maxOutputs, + inputPolicy: inputs.policy, + outputPolicy: outputs.policy, 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 4a461fdd..47e25a74 100644 --- a/src/lib/types/nodes.ts +++ b/src/lib/types/nodes.ts @@ -23,6 +23,8 @@ export interface PortDefinition { name: string; direction: PortDirection; color?: string; + /** Label pathsim addresses the port by, for the fixed ports of a pathsim block */ + key?: string; /** Signals of a port that is a pathsim `Carrier`, a bus of its channels */ bus?: BusStructure; } @@ -31,12 +33,24 @@ export interface PortDefinition { export interface PortInstance { id: string; // Unique port ID: `${nodeId}-${direction}-${index}` nodeId: string; + /** Display name, editable by the user */ name: string; direction: PortDirection; index: number; color: string; + /** Label pathsim addresses the port by; ports without one are addressed by index */ + key?: string; + /** Signals of a port that is a pathsim `Carrier`, a bus of its channels */ + bus?: BusStructure; } +/** + * 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 + */ +export type PortPolicy = 'fixed' | 'variable'; + /** Parameter type annotation (mirrors Python type hints) */ export type ParamType = 'number' | 'integer' | 'boolean' | 'string' | 'array' | 'callable' | 'any'; @@ -74,8 +88,8 @@ export interface NodeTypeDefinition { outputs: PortDefinition[]; minInputs: number; // minimum number of input ports (default 1) minOutputs: number; // minimum number of output ports (default 1) - maxInputs: number | null; // null = unlimited - maxOutputs: number | null; + inputPolicy: PortPolicy; + outputPolicy: PortPolicy; syncPorts?: boolean; // When true, output count always equals input count (parallel paths) }; diff --git a/tests/test_bus_expansion.py b/tests/test_bus_expansion.py index ef4e32d8..188bae01 100644 --- a/tests/test_bus_expansion.py +++ b/tests/test_bus_expansion.py @@ -6,7 +6,7 @@ import pytest from pathview.buses import expand_buses, is_bus_block -from pathview.converter import generate_python, load_registry +from pathview.converter import generate_python, load_registry, with_port_structure FIXTURES = json.loads((Path(__file__).parent / "fixtures" / "bus_expansion.json").read_text()) REGISTRY_PATH = Path(__file__).parent.parent / "pathview" / "data" / "registry.json" @@ -15,6 +15,11 @@ REGISTRY = FIXTURES["registry"] +def _load(scenario): + """A scenario as a saved file is loaded: its ports get their structure from the registry.""" + return [with_port_structure(n, REGISTRY) for n in scenario["nodes"]], scenario["connections"] + + def _endpoint(connection, side): channel = connection.get(f"{side}Channel") port = f"{connection[f'{side}NodeId']}:{connection[f'{side}PortIndex']}" @@ -45,7 +50,7 @@ def _any_bus_block(nodes): @pytest.mark.parametrize("scenario", FIXTURES["scenarios"], ids=lambda s: s["name"]) def test_expansion_matches_fixture(scenario): - nodes, connections = expand_buses(scenario["nodes"], scenario["connections"], REGISTRY) + nodes, connections = expand_buses(*_load(scenario)) expected = {key: sorted(value) for key, value in scenario["expected"].items()} assert _levels(nodes, connections) == expected assert not _any_bus_block(nodes) @@ -53,9 +58,10 @@ def test_expansion_matches_fixture(scenario): def test_model_without_buses_is_unchanged(): scenario = next(s for s in FIXTURES["scenarios"] if "without buses" in s["name"]) - nodes, connections = expand_buses(scenario["nodes"], scenario["connections"], REGISTRY) - assert nodes is scenario["nodes"] - assert connections is scenario["connections"] + loaded, wires = _load(scenario) + nodes, connections = expand_buses(loaded, wires) + assert nodes is loaded + assert connections is wires def test_converter_generates_no_bus_blocks(): diff --git a/tests/test_converter.py b/tests/test_converter.py index 01780fbf..666120f1 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -7,7 +7,7 @@ from pathsim.blocks._block import Block from pathsim.utils.carrier import Carrier -from pathview.converter import generate_python, load_registry, port_key +from pathview.converter import generate_python, load_registry, port_key, with_port_structure sys.path.insert(0, str(Path(__file__).parent.parent / "scripts")) from pathview_introspect import extract_block # noqa: E402 @@ -15,8 +15,12 @@ REGISTRY = load_registry(Path(__file__).parent.parent / "pathview" / "data" / "registry.json") -def node(node_id, node_type, **params): - return {"id": node_id, "type": node_type, "name": node_id, "params": params} +def node(node_id, node_type, inputs=(), outputs=(), **params): + """A node as saved before ports carried their structure: ports with display names only.""" + return { + "id": node_id, "type": node_type, "name": node_id, "params": params, + "inputs": [{"name": name} for name in inputs], "outputs": [{"name": name} for name in outputs], + } def wire(source, source_port, target, target_port): @@ -28,17 +32,35 @@ def wire(source, source_port, target, target_port): def test_port_key(): - #labeled ports by label, variable ports by index - assert port_key(REGISTRY, "Atan2", "inputs", 1) == "b" - assert port_key(REGISTRY, "Atan2", "outputs", 0) == "y" - assert port_key(REGISTRY, "Scope", "inputs", 2) == 2 - assert port_key(REGISTRY, "Unknown", "inputs", 0) == 0 + #labeled ports by the label they carry, whatever their display name, others by index + atan = {"inputs": [{"name": "y", "key": "a"}, {"name": "denominator", "key": "b"}], "outputs": [{"name": "out 0", "key": "y"}]} + assert port_key(atan, "inputs", 1) == "b" + assert port_key(atan, "outputs", 0) == "y" + assert port_key({"inputs": [{"name": "in 0"}, {"name": "in 1"}, {"name": "in 2"}]}, "inputs", 2) == 2 + assert port_key({}, "inputs", 0) == 0 + + +def test_port_structure_from_registry(): + #saved display names do not tell the key, the registry does, by index + atan = with_port_structure(node("angle", "Atan2", inputs=["in 0", "in 1"], outputs=["out 0"]), REGISTRY) + assert [p["key"] for p in atan["inputs"]] == ["a", "b"] + assert atan["outputs"][0] == {"name": "out 0", "key": "y"} + + #a key a port carries stays, variable ports and unknown types get none + kept = with_port_structure({**node("c", "Constant"), "outputs": [{"name": "out", "key": "kept"}]}, REGISTRY) + assert kept["outputs"][0]["key"] == "kept" + assert "key" not in with_port_structure(node("s", "Scope", inputs=["in 0"]), REGISTRY)["inputs"][0] + assert "key" not in with_port_structure(node("u", "Unknown", inputs=["in 0"]), REGISTRY)["inputs"][0] + + #nodes inside subsystems as well + sub = {**node("sub", "Subsystem"), "graph": {"nodes": [node("c", "Constant", outputs=["out 0"])], "connections": []}} + assert with_port_structure(sub, REGISTRY)["graph"]["nodes"][0]["outputs"][0]["key"] == "out" def test_script_builds(): pvm = {"version": "1.0.0", "graph": { - "nodes": [node("x", "Constant", value="1.0"), node("y", "Constant", value="2.0"), - node("angle", "Atan2"), node("scope", "Scope")], + "nodes": [node("x", "Constant", outputs=["out 0"], value="1.0"), node("y", "Constant", outputs=["out 0"], value="2.0"), + node("angle", "Atan2", inputs=["in 0", "in 1"], outputs=["out 0"]), node("scope", "Scope", inputs=["in 0"])], "connections": [wire("x", 0, "angle", 1), wire("y", 0, "angle", 0), wire("angle", 0, "scope", 0)], }} code = generate_python(pvm, REGISTRY) @@ -87,7 +109,7 @@ def test_carrier_script_builds(): {**node("st", "Stream"), "outputs": [{"name": "out"}]}, {**node("tk", "Tank"), "inputs": [{"name": "in"}, {"name": "Q"}]}, {**node("sel", "BusSelector", signals=["T"]), "inputs": [{"name": "in 0"}], "outputs": [{"name": "T"}]}, - node("q", "Constant", value="4.0"), node("scope", "Scope"), + node("q", "Constant", outputs=["out 0"], value="4.0"), node("scope", "Scope", inputs=["in 0"]), ], "connections": [ wire("st", 0, "tk", 0), wire("q", 0, "tk", 1),