Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions docs/pvm-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,20 +131,23 @@ Ports define the input/output connection points on a node.
"name": "in 0",
"direction": "input",
"index": 0,
"color": "#969696"
"color": "#969696",
"key": "in"
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `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

Expand Down Expand Up @@ -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`.

Expand Down
31 changes: 14 additions & 17 deletions pathview/buses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
)

Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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))]
Expand Down
74 changes: 49 additions & 25 deletions pathview/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {}
Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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", {})
Expand Down Expand Up @@ -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("")
Expand Down
54 changes: 35 additions & 19 deletions src/lib/bus/expand.test.ts
Original file line number Diff line number Diff line change
@@ -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];
Expand All @@ -19,13 +21,26 @@ type Block = {
outputBuses?: Record<string, BusStructure>;
};

/** Carrier signals from the block types of the fixture, in the format of registry.json */
const blocks = fixtures.registry.blocks as Record<string, Block>;
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<string, Block>)) {
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}]`;
Expand All @@ -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[]
};
}
Expand All @@ -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<string, string[]>).map(([key, value]) => [
key,
Expand All @@ -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');
Expand All @@ -94,27 +110,27 @@ 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');
expect(busWiringProblem(analysis, root, 'Cr', 0, 'Tk', 1)).toBe('bus-into-block');

// 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');
Expand All @@ -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(['']);
Expand Down
Loading
Loading