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
6 changes: 4 additions & 2 deletions docs/pvm-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,11 @@ In PathSim Python code, subsystems map to `Subsystem(blocks=[...], connections=[
- A subsystem port carrying a bus becomes one port index per leaf signal, in bus order, on the Subsystem and on its Interface. Port indices after it shift accordingly.
- Wiring that cannot be resolved is left out: a bus into a block that is not a bus block or subsystem, a picked signal missing from the bus, or a wire loop through bus blocks.

Editors should not create such wiring: a bus may only enter a Bus Creator, a Bus Selector or a subsystem port, and a Bus Selector only takes a bus. PathView rejects these wires while connecting and draws existing ones as errors.
A port with `bus` is a PathSim carrier: a bus into it is resolved to one connection per channel, a wire from a carrier port to a carrier port stays one connection.

The reference implementations are `src/lib/bus/expand.ts` and `pathview/buses.py`; `tests/fixtures/bus_expansion.json` lists the expected wiring for each case.
Editors should not create such wiring: a bus may only enter a Bus Creator, a Bus Selector, a subsystem port or a carrier port, and a Bus Selector only takes a bus. A carrier port takes what PathSim connects to it: one signal per channel, and where a signal comes from a channel with a key and meets a channel with a key, the same key. Signals from ports without `bus`, from channels named by their position and through subsystem ports have no key. PathView rejects these wires while connecting and draws existing ones as errors.

The reference implementations are `src/lib/bus/expand.ts` and `pathview/buses.py`; `tests/fixtures/bus_expansion.json` lists the expected wiring for each case, and wires into carrier ports with the verdict of PathSim.

---

Expand Down
8 changes: 8 additions & 0 deletions pathview/buses.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ def port_bus(node: dict, direction: str, index: int):
return ports[index].get("bus") if index < len(ports) else None


def channel_key(carrier, channel: int) -> str | None:
"""Name of a channel of a carrier port in pathsim: its key, or None for a
channel without key, as those of a pathsim `Vector`, whose signals are
named by their position. Same rule as `channelKey` in the editor."""
name = carrier[channel]["name"] if carrier and channel < len(carrier) else None
return None if name is None or name == str(channel) else name


def is_bus_block(node: dict) -> bool:
return node.get("type") in (BUS_CREATOR, BUS_SELECTOR)

Expand Down
7 changes: 3 additions & 4 deletions pathview/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from pathlib import Path
from typing import Any

from pathview.buses import expand_buses, port_bus
from pathview.buses import channel_key, expand_buses, port_bus


# =============================================================================
Expand Down Expand Up @@ -113,9 +113,8 @@ def port_reference(var_name: str, node: dict, direction: str, index: int, channe
port = f"{var_name}[{json.dumps(port_key(node, direction, index))}]"
if channel is None:
return port
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)}]"
key = channel_key(port_bus(node, direction, index), channel)
return f"{port}[{channel if key is None else json.dumps(key)}]"


def group_connections_by_source(connections: list[dict], nodes: list[dict], node_vars: dict[str, str]) -> list[dict]:
Expand Down
19 changes: 13 additions & 6 deletions src/lib/bus/expand.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,26 +108,33 @@ describe('bus expansion', () => {
expect(busWiringProblem(analysis, root, 'S', 0, 'Scope', 0)).toBeNull();
});

it('takes a bus into a carrier port only with the signals of the carrier', () => {
it('keeps buses and plain signals at the ports that take them', () => {
const creator = load(fixtures.scenarios.find((s) => s.name === 'bus creator into a carrier port')!);
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);
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);
expect(busWiringProblem(streams, streams.root, 'St', 0, 'S', 0)).toBeNull();
expect(busWiringProblem(streams, streams.root, 'St', 0, 'Scope', 0)).toBe('bus-into-block');
});

describe('wires into carrier ports, with the verdict of pathsim', () => {
const wiring = load(fixtures.wiring as unknown as Scenario);
const analysis = analyzeBuses(wiring.nodes, wiring.connections);
for (const { wire, accepted, name } of fixtures.wiring.cases) {
it(name, () => {
const c = wiring.connections.find((connection) => connection.id === wire)!;
const problem = busWiringProblem(analysis, analysis.root, c.sourceNodeId, c.sourcePortIndex, c.targetNodeId, c.targetPortIndex);
expect(problem === null).toBe(accepted);
});
}
});

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);
Expand Down
154 changes: 89 additions & 65 deletions src/lib/bus/expand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ export function portBus(node: NodeInstance, direction: PortDirection, index: num
return nodePort(node, direction, index)?.bus ?? null;
}

/**
* Name of a channel of a carrier port in pathsim: its key, or null for a
* channel without key, as those of a pathsim `Vector`, whose signals are
* named by their position
*/
export function channelKey(carrier: BusStructure, channel: number): string | null {
const name = carrier?.[channel]?.name;
return name === undefined || name === String(channel) ? null : name;
}

/** A connection after bus expansion; a channel is the position of a single signal within a carrier port */
export interface ExpandedConnection extends Connection {
sourceChannel?: number;
Expand Down Expand Up @@ -210,71 +220,6 @@ export function analyzeBuses(nodes: NodeInstance[], connections: Connection[]) {
}
}

/** Level at a subsystem path from the root, by subsystem IDs */
function levelAt(path: string[]): BusLevel | null {
let level: BusLevel | undefined = root;
for (const id of path) {
level = level?.children.get(id);
if (!level) return null;
}
return level;
}

return { root, levelAt, structureIn, structureOut, elementNames };
}

export type BusAnalysis = ReturnType<typeof analyzeBuses>;

/** Why a wire breaks the bus rules */
export type BusWiringProblem = 'bus-into-block' | 'signal-into-selector' | 'signal-into-carrier' | 'bus-mismatch';

/**
* A bus may only enter a Bus Creator, a Bus Selector, a subsystem port or a
* carrier port, a Bus Selector only takes a bus, and a carrier port only a bus
* with its signals in its order. Returns the rule a wire from the source port to
* the target port breaks, or null if it keeps them.
*/
export function busWiringProblem(
analysis: BusAnalysis,
level: BusLevel,
sourceNodeId: string,
sourcePort: number,
targetNodeId: string,
targetPort: number
): BusWiringProblem | null {
const target = level.nodes.get(targetNodeId);
if (!target) return null;
const structure = analysis.structureOut(level, sourceNodeId, sourcePort);
switch (target.type) {
case NODE_TYPES.BUS_CREATOR:
case NODE_TYPES.SUBSYSTEM:
case NODE_TYPES.INTERFACE:
return null;
case NODE_TYPES.BUS_SELECTOR:
return structure ? null : 'signal-into-selector';
default: {
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';
}
}
}

/**
* The model without bus blocks, for code generation. Models without buses are
* returned unchanged. Connections that carry several signals are split, with
* IDs suffixed by the signal index. A wire between two plain blocks stays as it
* is, also from carrier to carrier. Wiring that cannot be resolved, such as a
* bus into a plain block or a signal missing from a bus, is left out.
*/
export function expandBuses(
nodes: NodeInstance[],
connections: Connection[]
): { nodes: NodeInstance[]; connections: ExpandedConnection[] } {
if (!containsBuses(nodes)) return { nodes, connections };

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 }));
Expand Down Expand Up @@ -363,6 +308,85 @@ export function expandBuses(
}
}

/** Level at a subsystem path from the root, by subsystem IDs */
function levelAt(path: string[]): BusLevel | null {
let level: BusLevel | undefined = root;
for (const id of path) {
level = level?.children.get(id);
if (!level) return null;
}
return level;
}

return { root, levelAt, structureIn, structureOut, elementNames, resolveOut, inputSlots };
}

export type BusAnalysis = ReturnType<typeof analyzeBuses>;

/** Why a wire breaks the bus rules */
export type BusWiringProblem = 'bus-into-block' | 'signal-into-selector' | 'signal-into-carrier' | 'bus-mismatch';

/**
* A bus may only enter a Bus Creator, a Bus Selector, a subsystem port or a
* carrier port, and a Bus Selector only takes a bus. A carrier port takes what
* pathsim connects to it (`Connection._validate_dimensions`): one signal per
* channel, and where a signal comes from a channel with a key and the channel
* it meets has one, the same key. Signals from plain ports, channels without
* key and signals through subsystem ports have none. Returns the rule a wire
* from the source port to the target port breaks, or null if it keeps them.
*/
export function busWiringProblem(
analysis: BusAnalysis,
level: BusLevel,
sourceNodeId: string,
sourcePort: number,
targetNodeId: string,
targetPort: number
): BusWiringProblem | null {
const target = level.nodes.get(targetNodeId);
if (!target) return null;
const structure = analysis.structureOut(level, sourceNodeId, sourcePort);
switch (target.type) {
case NODE_TYPES.BUS_CREATOR:
case NODE_TYPES.SUBSYSTEM:
case NODE_TYPES.INTERFACE:
return null;
case NODE_TYPES.BUS_SELECTOR:
return structure ? null : 'signal-into-selector';
default: {
const carrier = portBus(target, 'input', targetPort);
if (!carrier) return structure ? 'bus-into-block' : null;
const sources = analysis.resolveOut(level, sourceNodeId, sourcePort);
if (sources.length !== carrier.length) return structure ? 'bus-mismatch' : 'signal-into-carrier';
const sourceKey = (endpoint: (typeof sources)[number]) => {
const node = endpoint && endpoint.channel !== undefined ? level.nodes.get(endpoint.nodeId) : undefined;
return node ? channelKey(portBus(node, 'output', endpoint!.port), endpoint!.channel!) : null;
};
const meets = sources.every((endpoint, i) => {
const a = sourceKey(endpoint);
const b = channelKey(carrier, i);
return a === null || b === null || a === b;
});
return meets ? null : 'bus-mismatch';
}
}
}

/**
* The model without bus blocks, for code generation. Models without buses are
* returned unchanged. Connections that carry several signals are split, with
* IDs suffixed by the signal index. A wire between two plain blocks stays as it
* is, also from carrier to carrier. Wiring that cannot be resolved, such as a
* bus into a plain block or a signal missing from a bus, is left out.
*/
export function expandBuses(
nodes: NodeInstance[],
connections: Connection[]
): { nodes: NodeInstance[]; connections: ExpandedConnection[] } {
if (!containsBuses(nodes)) return { nodes, connections };

const { root, resolveOut, inputSlots } = analyzeBuses(nodes, connections);

function expandLevel(level: BusLevel): { nodes: NodeInstance[]; connections: ExpandedConnection[] } {
const expandedNodes: NodeInstance[] = [];
for (const node of level.nodeList) {
Expand Down
6 changes: 3 additions & 3 deletions src/lib/pyodide/codeBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ 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';
import { channelKey, type ExpandedConnection } from '$lib/bus/expand';

/** Options for parameter string generation */
export interface ParamStringOptions {
Expand Down Expand Up @@ -84,8 +84,8 @@ export function portKey(node: NodeInstance, direction: PortDirection, index: num
function portReference(node: NodeInstance, varName: string, direction: PortDirection, index: number, channel?: number): string {
const port = `${varName}[${JSON.stringify(portKey(node, direction, index))}]`;
if (channel === undefined) return port;
const name = nodePort(node, direction, index)?.bus?.[channel]?.name;
return `${port}[${name === undefined || name === String(channel) ? channel : JSON.stringify(name)}]`;
const key = channelKey(nodePort(node, direction, index)?.bus ?? null, channel);
return `${port}[${key === null ? channel : JSON.stringify(key)}]`;
}

/**
Expand Down
Loading
Loading