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
2 changes: 1 addition & 1 deletion pathview/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def generate_param_string(params: dict, valid_params: set[str], multi_line: bool


def with_port_structure(node: dict, registry: dict) -> dict:
"""Fill the pathsim key and the carrier channels of the fixed ports of a
"""Fill the pathsim key and the carrier channels of the labeled ports of a
node from the registry, by index, recursing into subsystems. For files
saved before ports carried their structure: the saved names are display
names (e.g. "out 0" for the label "out") and do not tell the key. Ports
Expand Down
4 changes: 3 additions & 1 deletion pathview/data/registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,9 @@
"inputs": [
"in"
],
"outputs": null
"outputs": [
"out_0"
]
},
"LUT": {
"blockClass": "LUT",
Expand Down
6 changes: 4 additions & 2 deletions scripts/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,9 @@ def _extract_block(self, cls, config: dict) -> dict:
"inputs": block["inputs"],
"outputs": block["outputs"],
"icon": block["icon"],
#only for blocks with carrier ports, the file stays as it was otherwise
**{key: block[key] for key in ("inputBuses", "outputBuses") if block[key]},
#only for blocks with carrier ports or parameter dependent ports,
#the file stays as it was otherwise
**{key: block[key] for key in ("inputBuses", "outputBuses", "portParameters") if block[key]},
}

def _import_module(self, import_path: str) -> Any:
Expand Down Expand Up @@ -632,6 +633,7 @@ def write_blocks(self, blocks: dict, config: dict, import_paths: dict[str, str]
" icon: string | null; // SVG icon from Block.icon(), null if the block has none",
" inputBuses?: Record<string, BusStructure>; // signals of the ports that are carriers, by name",
" outputBuses?: Record<string, BusStructure>;",
" portParameters?: string[]; // parameters the ports depend on, the ports above are those of the defaults",
"}",
"",
"export const extractedBlocks: Record<string, ExtractedBlock> = ",
Expand Down
4 changes: 3 additions & 1 deletion scripts/generated/registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,9 @@
"inputs": [
"in"
],
"outputs": null
"outputs": [
"out_0"
]
},
"LUT": {
"blockClass": "LUT",
Expand Down
46 changes: 38 additions & 8 deletions scripts/pathview_introspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,27 @@ def process_port_buses(labels):
}


def process_ports(input_labels, output_labels):
"""Ports of a block from its input and output port labels, in the shape
the editor reads: the port names and the channels of carrier ports."""
return {
"inputs": process_port_labels(input_labels),
"outputs": process_port_labels(output_labels),
"inputBuses": process_port_buses(input_labels),
"outputBuses": process_port_buses(output_labels),
}


def instance_ports(block):
"""Ports of a block instance, which differ from those of its class for
blocks whose ports depend on their parameters (`port_parameters`).
None for a pathsim whose `info()` does not report instances."""
info = block.info()
if "port_parameters" not in info:
return None
return process_ports(info.get("input_port_labels"), info.get("output_port_labels"))


# --- Class detection (runtime needs heuristics) --------------------------


Expand Down Expand Up @@ -267,6 +288,19 @@ def extract_block(cls):

if info is not None:
rst = (info.get("description") or raw_doc).strip()

#blocks whose ports depend on their parameters start with the ports
#of an instance with the default parameters
port_parameters = list(info.get("port_parameters") or ())
ports = None
if port_parameters:
try:
ports = instance_ports(cls())
except Exception:
ports = None
if ports is None:
ports = process_ports(info.get("input_port_labels"), info.get("output_port_labels"))

params = []
for pname, meta in (info.get("parameters") or {}).items():
default = meta.get("default") if isinstance(meta, dict) else None
Expand All @@ -280,10 +314,8 @@ def extract_block(cls):
"className": cls.__name__,
"description": first_line(rst),
"docstringHtml": rst_to_html(rst),
"inputs": process_port_labels(info.get("input_port_labels")),
"outputs": process_port_labels(info.get("output_port_labels")),
"inputBuses": process_port_buses(info.get("input_port_labels")),
"outputBuses": process_port_buses(info.get("output_port_labels")),
**ports,
"portParameters": port_parameters,
"params": params,
"icon": block_icon(cls),
}
Expand All @@ -293,10 +325,8 @@ def extract_block(cls):
"className": cls.__name__,
"description": first_line(raw_doc),
"docstringHtml": rst_to_html(raw_doc),
"inputs": process_port_labels(getattr(cls, "input_port_labels", None)),
"outputs": process_port_labels(getattr(cls, "output_port_labels", None)),
"inputBuses": process_port_buses(getattr(cls, "input_port_labels", None)),
"outputBuses": process_port_buses(getattr(cls, "output_port_labels", None)),
**process_ports(getattr(cls, "input_port_labels", None), getattr(cls, "output_port_labels", None)),
"portParameters": [],
"params": extract_params_from_signature(cls, raw_doc),
"icon": block_icon(cls),
}
Expand Down
21 changes: 15 additions & 6 deletions src/lib/nodes/defineNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ interface DefineNodeOptions {
minOutputs?: number;
inputPolicy?: PortPolicy; // default 'variable'
outputPolicy?: PortPolicy;
/** Parameters the ports depend on, for 'derived' ports */
portParameters?: string[];
syncPorts?: boolean; // When true, output count always equals input count

// Shape override (defaults based on category)
Expand All @@ -49,10 +51,15 @@ interface DefineNodeOptions {

/**
* Ports of a pathsim block in one direction from its introspected port labels:
* a list gives fixed ports named by their labels, `null` variable ports
* a list gives ports named by their labels, fixed, or derived for a block whose
* ports depend on its parameters, `null` variable ports
*/
export function portsFromLabels(labels: string[] | null | undefined): { names: string[] | undefined; policy: PortPolicy } {
return labels == null ? { names: undefined, policy: 'variable' } : { names: labels, policy: 'fixed' };
export function portsFromLabels(
labels: string[] | null | undefined,
portParameters?: string[]
): { names: string[] | undefined; policy: PortPolicy } {
if (labels == null) return { names: undefined, policy: 'variable' };
return { names: labels, policy: portParameters?.length ? 'derived' : 'fixed' };
}

/**
Expand All @@ -74,6 +81,7 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition {
minOutputs = 1,
inputPolicy = 'variable',
outputPolicy = 'variable',
portParameters,
syncPorts,
shape,
params = {}
Expand Down Expand Up @@ -104,14 +112,14 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition {
name: portName,
direction: 'input' as const,
color: PORT_COLORS.default,
...(labeled && inputPolicy === 'fixed' ? { key: portName } : {}),
...(labeled && inputPolicy !== 'variable' ? { key: portName } : {}),
...(inputBuses[portName] ? { bus: inputBuses[portName] } : {})
})),
outputs: outputs.map((portName) => ({
name: portName,
direction: 'output' as const,
color: PORT_COLORS.default,
...(labeled && outputPolicy === 'fixed' ? { key: portName } : {}),
...(labeled && outputPolicy !== 'variable' ? { key: portName } : {}),
...(outputBuses[portName] ? { bus: outputBuses[portName] } : {})
})),
minInputs,
Expand All @@ -121,6 +129,7 @@ export function defineNode(options: DefineNodeOptions): NodeTypeDefinition {
syncPorts
},

params: paramDefs
params: paramDefs,
...(portParameters?.length ? { portParameters } : {})
};
}
21 changes: 15 additions & 6 deletions src/lib/nodes/generated/blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,30 @@ export interface ExtractedBlock {
icon: string | null; // SVG icon from Block.icon(), null if the block has none
inputBuses?: Record<string, BusStructure>; // signals of the ports that are carriers, by name
outputBuses?: Record<string, BusStructure>;
portParameters?: string[]; // parameters the ports depend on, the ports above are those of the defaults
}

export const extractedBlocks: Record<string, ExtractedBlock> =
{
"Constant": {
"blockClass": "Constant",
"description": "Produces a constant output signal (SISO).",
"docstringHtml": "<p>Produces a constant output signal (SISO).</p>\n<div class=\"math\">\n\\begin{equation*}\ny(t) = const.\n\\end{equation*}\n</div>\n<div class=\"section\" id=\"parameters\">\n<h3>Parameters</h3>\n<dl class=\"docutils\">\n<dt>value <span class=\"classifier-delimiter\">:</span> <span class=\"classifier\">float</span></dt>\n<dd>constant defining block output</dd>\n</dl>\n</div>\n",
"description": "Produces a constant output signal.",
"docstringHtml": "<p>Produces a constant output signal.</p>\n<div class=\"math\">\n\\begin{equation*}\ny(t) = const.\n\\end{equation*}\n</div>\n<p>A scalar value gives a single output 'out', an array value one output\nper element, 'out_0', 'out_1', ...</p>\n<div class=\"section\" id=\"example\">\n<h3>Example</h3>\n<p>Constant boundary values for three channels, for example the inlet flows\nof a stream that is a carrier input of the block 'B':</p>\n<pre class=\"code python literal-block\">\n<span class=\"name\">C</span> <span class=\"operator\">=</span> <span class=\"name\">Constant</span><span class=\"punctuation\">([</span><span class=\"literal number float\">1.0</span><span class=\"punctuation\">,</span> <span class=\"literal number float\">0.5</span><span class=\"punctuation\">,</span> <span class=\"literal number float\">0.0</span><span class=\"punctuation\">])</span><span class=\"whitespace\">\n\n</span><span class=\"name\">Con</span> <span class=\"operator\">=</span> <span class=\"name\">Connection</span><span class=\"punctuation\">(</span><span class=\"name\">C</span><span class=\"punctuation\">[</span><span class=\"literal number integer\">0</span><span class=\"punctuation\">:</span><span class=\"literal number integer\">3</span><span class=\"punctuation\">],</span> <span class=\"name\">B</span><span class=\"punctuation\">[</span><span class=\"literal string double\">&quot;in&quot;</span><span class=\"punctuation\">])</span>\n</pre>\n</div>\n<div class=\"section\" id=\"parameters\">\n<h3>Parameters</h3>\n<dl class=\"docutils\">\n<dt>value <span class=\"classifier-delimiter\">:</span> <span class=\"classifier\">float, array_like</span></dt>\n<dd>constant defining block output, scalar or 1d array</dd>\n</dl>\n</div>\n",
"params": {
"value": {
"type": "integer",
"default": "1",
"description": "constant defining block output"
"description": "constant defining block output, scalar or 1d array"
}
},
"inputs": [],
"outputs": [
"out"
],
"icon": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 64\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><line x1=\"10\" y1=\"50\" x2=\"86\" y2=\"50\"/><line x1=\"10\" y1=\"10\" x2=\"10\" y2=\"54\"/><path d=\"M 14 14 L 82 14\"/></svg>\n"
"icon": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 64\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><line x1=\"10\" y1=\"50\" x2=\"86\" y2=\"50\"/><line x1=\"10\" y1=\"10\" x2=\"10\" y2=\"54\"/><path d=\"M 14 14 L 82 14\"/></svg>\n",
"portParameters": [
"value"
]
},
"Source": {
"blockClass": "Source",
Expand Down Expand Up @@ -1243,8 +1247,13 @@ export const extractedBlocks: Record<string, ExtractedBlock> =
"inputs": [
"in"
],
"outputs": null,
"icon": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 64\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <path d=\"M 18 32 H 40 C 52 32 50 20 62 20 H 78\"/>\n <path d=\"M 40 32 C 52 32 50 44 62 44 H 78\"/>\n <circle cx=\"40\" cy=\"32\" r=\"2.5\" fill=\"currentColor\" stroke=\"none\"/>\n</svg>\n"
"outputs": [
"out_0"
],
"icon": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 64\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <path d=\"M 18 32 H 40 C 52 32 50 20 62 20 H 78\"/>\n <path d=\"M 40 32 C 52 32 50 44 62 44 H 78\"/>\n <circle cx=\"40\" cy=\"32\" r=\"2.5\" fill=\"currentColor\" stroke=\"none\"/>\n</svg>\n",
"portParameters": [
"fractions"
]
},
"LUT": {
"blockClass": "LUT",
Expand Down
13 changes: 7 additions & 6 deletions src/lib/nodes/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ export function nodePort(node: NodeInstance, direction: PortDirection, index: nu
}

/**
* Fill the pathsim key and the carrier channels of the fixed ports of a node
* from its type definition, by index, recursing into subsystems. For nodes
* saved before ports carried their structure: the saved names are display
* names (e.g. "out 0" for the label "out") and do not tell the key. Ports that
* have a key, variable ports and unknown types are left as they are.
* Fill the pathsim key and the carrier channels of the labeled ports of a node
* (fixed, or derived with the ports of the default parameters) from its type
* definition, by index, recursing into subsystems. For nodes saved before ports
* carried their structure: the saved names are display names (e.g. "out 0" for
* the label "out") and do not tell the key. Ports that have a key, variable
* ports and unknown types are left as they are.
*/
export function withPortStructure(node: NodeInstance): NodeInstance {
let result = node;
Expand All @@ -28,7 +29,7 @@ export function withPortStructure(node: NodeInstance): NodeInstance {
for (const direction of ['input', 'output'] as const) {
const portsKey = direction === 'input' ? 'inputs' : 'outputs';
const policy = direction === 'input' ? typeDef.ports.inputPolicy : typeDef.ports.outputPolicy;
if (policy !== 'fixed') continue;
if (policy === 'variable') continue;
const defs = typeDef.ports[portsKey];
const ports = result[portsKey];
if (!ports.some((port, i) => port.key === undefined && (defs[i]?.key !== undefined || defs[i]?.bus))) continue;
Expand Down
5 changes: 3 additions & 2 deletions src/lib/nodes/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ function createNodeFromExtracted(
};
}

const inputs = portsFromLabels(extracted.inputs);
const outputs = portsFromLabels(extracted.outputs);
const inputs = portsFromLabels(extracted.inputs, extracted.portParameters);
const outputs = portsFromLabels(extracted.outputs, extracted.portParameters);

const definition = defineNode({
name,
Expand All @@ -192,6 +192,7 @@ function createNodeFromExtracted(
outputBuses: extracted.outputBuses,
inputPolicy: inputs.policy,
outputPolicy: outputs.policy,
portParameters: extracted.portParameters,
syncPorts: syncPortBlocks.has(name),
params
});
Expand Down
13 changes: 13 additions & 0 deletions src/lib/pyodide/codeBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import type { NodeInstance, PortDirection } from '$lib/nodes/types';
import { nodePort } from '$lib/nodes/ports';
import { nodeRegistry } from '$lib/nodes/registry';
import { blockImportPaths } from '$lib/nodes/generated/blocks';
import { enginePath } from '$lib/constants/engine';
import type { ExpandedConnection } from '$lib/bus/expand';

/** Options for parameter string generation */
Expand Down Expand Up @@ -53,6 +56,16 @@ export function generateParamString(
return parts.join(', ');
}

/**
* Module a block class is imported from: toolbox blocks carry their own
* import path, built-ins come from the static map, else core pathsim.blocks.
* enginePath() rewrites core pathsim paths to the active engine module
* (identity in the default pathsim build).
*/
export function blockImportPath(blockClass: string): string {
return enginePath(nodeRegistry.get(blockClass)?.importPath ?? blockImportPaths[blockClass] ?? 'pathsim.blocks');
}

/**
* Key of a block port in pathsim: the label the port carries, for the fixed
* ports of a pathsim block, else its index. Labeled ports go by label because
Expand Down
14 changes: 4 additions & 10 deletions src/lib/pyodide/pathsimRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import { eventRegistry } from '$lib/events/registry';
import { NODE_TYPES } from '$lib/constants/nodeTypes';
import { BLOCK_CATEGORY_ORDER } from '$lib/constants/python';
import { isSubsystem, isInterface } from '$lib/nodes/shapes';
import { blockImportPaths } from '$lib/nodes/generated/blocks';
import { ENGINE_MODULE, enginePath } from '$lib/constants/engine';
import { ENGINE_MODULE } from '$lib/constants/engine';
import { generateEngineSetup } from './engineCodegen';
import { graphStore, findParentSubsystem } from '$lib/stores/graph';
import { expandBuses, isBusBlock } from '$lib/bus/expand';
Expand All @@ -26,7 +25,8 @@ import {
generateParamString,
generateNamedConnections,
generateListDefinition,
sanitizeName
sanitizeName,
blockImportPath
} from './codeBuilder';

// Re-export sanitizeName for external use
Expand Down Expand Up @@ -165,13 +165,7 @@ function collectBlockImportGroups(nodes: NodeInstance[]): Map<string, Set<string
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) continue;

// Toolbox-registered blocks carry their own importPath; built-ins
// fall back to the static map. Last fallback is core pathsim.blocks.
// enginePath() rewrites core pathsim paths to the active engine module
// (identity in the default pathsim build).
const importPath = enginePath(
typeDef.importPath ?? blockImportPaths[typeDef.blockClass] ?? 'pathsim.blocks'
);
const importPath = blockImportPath(typeDef.blockClass);
if (!groups.has(importPath)) groups.set(importPath, new Set());
groups.get(importPath)!.add(typeDef.blockClass);
}
Expand Down
Loading
Loading